2023-10-03 18:14:42 +02:00
|
|
|
class DataSources::AdresseController < ApplicationController
|
|
|
|
def search
|
|
|
|
if params[:q].present? && params[:q].length > 3
|
2023-10-13 16:06:00 +02:00
|
|
|
response = fetch_results
|
|
|
|
|
|
|
|
if response.success?
|
|
|
|
results = JSON.parse(response.body, symbolize_names: true)
|
|
|
|
|
2024-04-02 15:41:36 +02:00
|
|
|
return render json: format_results(results)
|
2023-10-13 16:06:00 +02:00
|
|
|
end
|
2023-10-03 18:14:42 +02:00
|
|
|
end
|
2024-04-02 15:41:36 +02:00
|
|
|
|
|
|
|
render json: []
|
|
|
|
|
|
|
|
rescue JSON::ParserError => e
|
|
|
|
Sentry.set_extras(body: response.body, code: response.code)
|
|
|
|
Sentry.capture_exception(e)
|
|
|
|
render json: []
|
2023-10-03 18:14:42 +02:00
|
|
|
end
|
2023-10-13 16:06:00 +02:00
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def fetch_results
|
2024-03-04 08:28:43 +01:00
|
|
|
Typhoeus.get("#{API_ADRESSE_URL}/search", params: { q: params[:q], limit: 10 }, timeout: 3)
|
2023-10-13 16:06:00 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def format_results(results)
|
2024-03-01 16:46:59 +01:00
|
|
|
results[:features].flat_map do |feature|
|
|
|
|
if feature[:properties][:type] == 'municipality'
|
|
|
|
departement_code = feature[:properties][:context].split(',').first
|
|
|
|
APIGeoService.commune_postal_codes(departement_code, feature[:properties][:citycode]).map do |postcode|
|
|
|
|
feature.deep_merge(properties: { postcode:, label: "#{feature[:properties][:label]} (#{postcode})" })
|
|
|
|
end
|
|
|
|
else
|
|
|
|
feature
|
|
|
|
end
|
|
|
|
end.map do
|
2023-10-13 16:06:00 +02:00
|
|
|
{
|
|
|
|
label: _1[:properties][:label],
|
|
|
|
value: _1[:properties][:label],
|
2024-02-13 13:40:33 +01:00
|
|
|
data: _1
|
2023-10-13 16:06:00 +02:00
|
|
|
}
|
|
|
|
end
|
|
|
|
end
|
2023-10-03 18:14:42 +02:00
|
|
|
end
|