Sha256: 3b07b3b24a90881dccee91f199374419c2d30609b51d542764f912f90e592f1c

Contents?: true

Size: 1.52 KB

Versions: 2

Compression:

Stored size: 1.52 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

2 entries across 2 versions & 1 rubygems

Version Path
emarsys-api-0.3.0 lib/emarsys/api/base.rb
emarsys-api-0.2.0 lib/emarsys/api/base.rb