demarches-normaliennes/app/lib/api_entreprise/api.rb
2018-08-23 15:55:32 +02:00

69 lines
1.7 KiB
Ruby

class ApiEntreprise::API
ENTREPRISE_RESOURCE_NAME = "entreprises"
ETABLISSEMENT_RESOURCE_NAME = "etablissements"
EXERCICES_RESOURCE_NAME = "exercices"
RNA_RESOURCE_NAME = "associations"
TIMEOUT = 15
def initialize
end
def self.entreprise(siren, procedure_id)
call(ENTREPRISE_RESOURCE_NAME, siren, procedure_id)
end
def self.etablissement(siret, procedure_id)
call(ETABLISSEMENT_RESOURCE_NAME, siret, procedure_id)
end
def self.exercices(siret, procedure_id)
call(EXERCICES_RESOURCE_NAME, siret, procedure_id)
end
def self.rna(siret, procedure_id)
call(RNA_RESOURCE_NAME, siret, procedure_id)
end
def self.call(resource_name, siret_or_siren, procedure_id)
url = url(resource_name, siret_or_siren)
params = params(siret_or_siren, procedure_id)
response = Typhoeus.get(url,
ssl_verifypeer: false,
params: params,
timeout: TIMEOUT)
# Responses with a 206 codes are sometimes not useable,
# as the RNA calls often return a 206 with an error message,
# not a partial response
if response.success? && response.code != 206
JSON.parse(response.body, symbolize_names: true)
else
raise RestClient::ResourceNotFound
end
end
def self.url(resource_name, siret_or_siren)
[base_url, resource_name, siret_or_siren].join("/")
end
def self.params(siret_or_siren, procedure_id)
{
context: "demarches-simplifiees.fr",
recipient: siret_or_siren,
object: "procedure_id: #{procedure_id}",
token: token
}
end
private
def self.token
Rails.application.secrets.api_entreprise[:key]
end
def self.base_url
Rails.application.secrets.api_entreprise[:base_url]
end
end