Sha256: 78f9dde1d89278974c726fbe26f1e89d50fe385199d45ec57ca5e19254597bfa

Contents?: true

Size: 1.51 KB

Versions: 5

Compression:

Stored size: 1.51 KB

Contents

require 'escher-keypool'
require 'faraday'
require 'faraday_middleware'
require 'faraday_middleware/escher'

module Emarsys
  module Api
    class Base
      def client
        @client ||= Faraday.new(url: base_url) do |faraday|
          faraday.use FaradayMiddleware::Escher::RequestSigner, escher_config

          faraday.response :json, content_type: /\bjson$/
          faraday.response :json_fix

          faraday.adapter Faraday.default_adapter
        end
      end


      private

      def uri
        URI.join(Emarsys::Api.base_url, module_path)
      end

      def module_path
        ''
      end

      def base_url
        uri.to_s
      end

      def hostname
        uri.hostname
      end

      def escher_config
        {
          credential_scope: 'eu/suite/ems_request',
          host: hostname,
          options: ESCHER_AUTH_OPTIONS,
          active_key: -> { ::Escher::Keypool.new.get_active_key('suite') }
        }
      end

      def validate_response!(response)
        error_class = error_class_by_status response.status
        raise error_class.new(*parse_for_error(response)) if error_class
      end

      def error_class_by_status(status)
        case status
        when 200 then nil
        when 202, 423 then RecoverableError
        when 404 then IrrecoverableError
        when 400 then BadRequestError
        when 401 then UnauthorizedError
        else Error
        end
      end

      def parse_for_error(response)
        [response.body, response.status, nil]
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
emarsys-api-0.7.0 lib/emarsys/api/base.rb
emarsys-api-0.6.1 lib/emarsys/api/base.rb
emarsys-api-0.6.0 lib/emarsys/api/base.rb
emarsys-api-0.5.0 lib/emarsys/api/base.rb
emarsys-api-0.4.0 lib/emarsys/api/base.rb