return communes with the APIGeoService

This commit is contained in:
sebastiencarceles 2023-02-23 14:35:28 +01:00
parent 67bbacbb05
commit 83802a507a
3 changed files with 91 additions and 3 deletions

View file

@ -47,6 +47,25 @@ class APIGeoService
departements.find { _1[:name] == name }&.dig(:code)
end
def communes(departement_code)
get_from_api_geo(
"communes?codeDepartement=#{departement_code}",
additional_keys: { postal_codes: :codesPostaux }
).sort_by { I18n.transliterate(_1[:name]) }
end
def commune_name(departement_code, code)
communes(departement_code).find { _1[:code] == code }&.dig(:name)
end
def commune_code(departement_code, name)
communes(departement_code).find { _1[:name] == name }&.dig(:code)
end
def commune_postal_codes(departement_code, code)
communes(departement_code).find { _1[:code] == code }&.dig(:postal_codes)
end
def epcis(departement_code)
get_from_api_geo("epcis?codeDepartement=#{departement_code}").sort_by { I18n.transliterate(_1[:name]) }
end
@ -61,11 +80,16 @@ class APIGeoService
private
def get_from_api_geo(scope)
def get_from_api_geo(scope, additional_keys: {})
Rails.cache.fetch("api_geo_#{scope}", expires_in: 1.year) do
response = Typhoeus.get("#{API_GEO_URL}/#{scope}")
JSON.parse(response.body).map(&:symbolize_keys)
.map { { name: _1[:nom].tr("'", ''), code: _1[:code] } }
JSON.parse(response.body)
.map(&:symbolize_keys)
.map do |result|
data = { name: result[:nom].tr("'", ''), code: result[:code] }
additional_keys.each { |key, value| data = data.merge(key => result[value]) }
data
end
end
end

File diff suppressed because one or more lines are too long

View file

@ -43,6 +43,29 @@ describe APIGeoService do
end
end
describe 'communes', vcr: { cassette_name: 'api_geo_communes' } do
it 'return sorted results' do
expect(APIGeoService.communes('01').size).to eq(393)
expect(APIGeoService.communes('01').first).to eq(code: '01004', name: 'Ambérieu-en-Bugey', postal_codes: ['01500'])
expect(APIGeoService.communes('01').last).to eq(code: '01457', name: 'Vonnas', postal_codes: ['01540'])
end
end
describe 'commune_name', vcr: { cassette_name: 'api_geo_communes' } do
subject { APIGeoService.commune_name('01', '01457') }
it { is_expected.to eq('Vonnas') }
end
describe 'commune_code', vcr: { cassette_name: 'api_geo_communes' } do
subject { APIGeoService.commune_code('01', 'Vonnas') }
it { is_expected.to eq('01457') }
end
describe 'commune_postal_codes', vcr: { cassette_name: 'api_geo_communes' } do
subject { APIGeoService.commune_postal_codes('01', '01457') }
it { is_expected.to eq(['01540']) }
end
describe 'epcis', vcr: { cassette_name: 'api_geo_epcis' } do
it 'return sorted results' do
expect(APIGeoService.epcis('01').size).to eq(17)