demarches-normaliennes/app/lib/api_education/annuaire_education_adapter.rb

46 lines
1.2 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
2021-01-13 18:58:59 +01:00
require 'json_schemer'
2020-08-05 18:40:47 +02:00
class APIEducation::AnnuaireEducationAdapter
2021-01-13 18:58:59 +01:00
class InvalidSchemaError < ::StandardError
def initialize(errors)
super(errors.map(&:to_json).join("\n"))
end
end
def initialize(id)
@id = id
2021-01-13 18:58:59 +01:00
end
def to_params
record = data_source[:records].first
if record.present?
properties = record[:fields].merge({ geometry: record[:geometry] }).deep_stringify_keys
2021-06-01 15:14:42 +02:00
# API sends numbers as strings sometime. Try to parse.
if properties['code_type_contrat_prive'].is_a? String
code = properties['code_type_contrat_prive'].to_i
if code.to_s == properties['code_type_contrat_prive']
properties['code_type_contrat_prive'] = code
end
end
2021-01-13 18:58:59 +01:00
if schemer.valid?(properties)
properties
else
errors = schemer.validate(properties).to_a
raise InvalidSchemaError.new(errors)
end
end
end
private
def data_source
2020-08-05 18:40:47 +02:00
@data_source ||= JSON.parse(APIEducation::API.get_annuaire_education(@id), symbolize_names: true)
2021-01-13 18:58:59 +01:00
end
def schemer
@schemer ||= JSONSchemer.schema(Rails.root.join('app/schemas/etablissement-annuaire-education.json'))
end
end