# frozen_string_literal: true require_relative "nuva/version" require_relative "nuva/NuvaDatabase_pb" require_relative "nuva/repository" require_relative "nuva/queries" require "net/http" require "json" require "ostruct" module Nuva class Nuva attr_reader :repositories attr_reader :queries def initialize(db) @db = db @repositories = OpenStruct.new @repositories.vaccines = VaccineRepository.new db.vaccines @repositories.valences = ValenceRepository.new db.valences @repositories.diseases = DiseaseRepository.new db.diseases @repositories.freeze @queries = OpenStruct.new @queries.valences_by_vaccine = ::Nuva::Queries::ValencesByVaccineQuery.new @repositories @queries.vaccines_by_valence = ::Nuva::Queries::VaccinesByValenceQuery.new @repositories @queries.vaccines_by_disease = ::Nuva::Queries::VaccinesByDiseaseQuery.new @repositories @queries.valences_by_disease = ::Nuva::Queries::ValencesByDiseaseQuery.new @repositories @queries.diseases_by_vaccine = ::Nuva::Queries::DiseasesByVaccineQuery.new @repositories @queries.diseases_by_valence = ::Nuva::Queries::DiseasesByValenceQuery.new @repositories @queries.vaccine_fuzzy_search = ::Nuva::Queries::VaccineFuzzySearchQuery.new @repositories @queries.lookup_vaccine_by_code = ::Nuva::Queries::LookupVaccineByCodeQuery.new @repositories @queries.lookup_equivalent_vaccines = ::Nuva::Queries::LookupEquivalentVaccinesQuery.new @repositories @queries.lookup_generalized_vaccines = ::Nuva::Queries::LookupGeneralizedVaccinesQuery.new @repositories, @queries.valences_by_vaccine @queries.all_nomenclatures = ::Nuva::Queries::AllNomenclaturesQuery.new @repositories @queries.all_code_by_nomenclature = ::Nuva::Queries::AllCodeByNomenclatureQuery.new @repositories @queries.freeze end def version @db.version end def inspect "#" end class << self DEFAULT_CDN_URI = URI("https://nuva.svc.edge.scw.cloud") def load(cdn_uri: DEFAULT_CDN_URI, lang: "en", hash: nil) init_http(cdn_uri) do |http| # Fetch version manifest if necessary hash ||= fetch_latest_version_hash(http:) response = http.get("/proto/#{hash}_en.db") ::Nuva::Nuva.new(::Nuva::NuvaDatabase.decode(response.body)) end end def fetch_latest_version_hash(cdn_uri: DEFAULT_CDN_URI, http: nil) if http.nil? http = init_http(cdn_uri) passed_http = false end response = http.get("/versions/last.json") hash = JSON.parse(response.body)["dump_hash"] http.finish unless passed_http hash end def load_from_file(path) Nuva.new(NuvaDatabase.decode(File.read(path))) end private def init_http(cdn_uri, &block) Net::HTTP.start( cdn_uri.host, cdn_uri.port, use_ssl: cdn_uri.scheme == "https", &block ) end end end end