demarches-normaliennes/app/lib/api_geo/api.rb

58 lines
1.4 KiB
Ruby
Raw Normal View History

2018-10-15 21:01:37 +02:00
class ApiGeo::API
2018-10-23 15:35:03 +02:00
TIMEOUT = 15
CACHE_DURATION = 1.day
2018-10-23 15:35:03 +02:00
2018-10-15 17:26:06 +02:00
def self.regions
url = [API_GEO_URL, "regions"].join("/")
2018-10-23 15:35:03 +02:00
call(url, { fields: :nom })
2018-10-15 17:26:06 +02:00
end
2018-10-15 16:30:27 +02:00
2018-10-15 17:26:06 +02:00
def self.departements
url = [API_GEO_URL, "departements"].join("/")
2018-10-23 15:35:03 +02:00
call(url, { fields: :nom })
2018-10-15 17:26:06 +02:00
end
2018-10-15 16:30:27 +02:00
2018-10-15 17:26:06 +02:00
def self.pays
2018-10-23 15:35:03 +02:00
parse(File.open('app/lib/api_geo/pays.json').read)
2018-10-15 17:26:06 +02:00
end
2018-10-15 16:30:27 +02:00
2018-10-23 15:37:13 +02:00
def self.search_rpg(geojson)
url = [API_GEO_SANDBOX_URL, "rpg", "parcelles", "search"].join("/")
call(url, geojson, :post)
end
2018-10-15 17:26:06 +02:00
private
2018-10-15 16:30:27 +02:00
2018-10-23 15:35:03 +02:00
def self.parse(body)
JSON.parse(body, symbolize_names: true)
end
def self.call(url, body, method = :get)
# The cache engine is stored, because as of Typhoeus 1.3.1 the cache engine instance
# is included in the computed `cache_key`.
# (Which means that when the cache instance changes, the cache is invalidated.)
@typhoeus_cache ||= Typhoeus::Cache::SuccessfulRequestsRailsCache.new
2018-10-23 15:35:03 +02:00
response = Typhoeus::Request.new(
url,
method: method,
params: method == :get ? body : nil,
body: method == :post ? body : nil,
timeout: TIMEOUT,
accept_encoding: 'gzip',
headers: {
'Accept' => 'application/json',
'Accept-Encoding' => 'gzip, deflate'
}.merge(method == :post ? { 'Content-Type' => 'application/json' } : {}),
cache: @typhoeus_cache,
cache_ttl: CACHE_DURATION
2018-10-23 15:35:03 +02:00
).run
if response.success?
parse(response.body)
else
nil
end
2018-10-15 16:30:27 +02:00
end
end