module Ecoportal module API module Common module GraphQL class HttpClient < Common::Client class << self def base_url(host) "#{protocol(host)}://#{host}" end def protocol(host) host.match(/^localhost|^127\.0\.0\.1/)? "http" : "https" end end attr_reader :host, :version def initialize( api_key: nil, version: "v1", host: "live.ecoportal.com", logger: ::Logger.new(IO::NULL), response_logging: false ) super( api_key: api_key, version: version, host: host, logger: logger, response_logging: response_logging ) end def refresh_key(value) @api_key = value end # Creates a HTTP object adding the `X-ApiKey` or `X-ECOPORTAL-API-KEY` param to the header, depending on the API version. # @note It configures HTTP so it only allows body data in json format. # @return [HTTP] HTTP object. def base_request @base_request ||= case @version when NilClass HTTP.accept(:json) when "v2" HTTP.headers("X-ECOPORTAL-API-KEY" => key_token).accept(:json) when "graphql" HTTP.headers("Authorization" => "Bearer #{key_token}").accept(:json) else HTTP.headers("X-ApiKey" => key_token).accept(:json) end end # Full URl builder of the request # @param path [String] the tail that completes the url of the request. # @return [String] the final url. def url_for(path) version? ? "#{base_url_api}#{path}" : "#{base_url}#{path}" end private def version? !!@version end def protocol @protocol ||= self.class.protocol(host) end def base_url @base_url ||= self.class.base_url(host) end def base_url_api @base_url_api ||= "#{base_url}/api/#{version}" end def key_token if @api_key.nil? || @api_key.match(/\A\W*\z/) if (version == "v0") && (key = ENV['ORG_INT_KEY']) key else puts "Api-key missing!" end else @api_key end end end end end end end