Sha256: e3d10b392169178d4cb1082169f44f958fd8aecc4779d07fddc69faef9db3195

Contents?: true

Size: 1.6 KB

Versions: 3

Compression:

Stored size: 1.6 KB

Contents

require 'faraday_middleware'
require_relative 'error'

module TicketingHub
  class ErrorHandler < Faraday::Response::Middleware
    ERROR_MAP = {
      400 => TicketingHub::BadRequest,
      401 => TicketingHub::Unauthorized,
      403 => TicketingHub::Forbidden,
      404 => TicketingHub::NotFound,
      405 => TicketingHub::Gone,
      406 => TicketingHub::NotAcceptable,
      422 => TicketingHub::UnprocessableEntity,
      500 => TicketingHub::InternalServerError,
      501 => TicketingHub::NotImplemented,
      502 => TicketingHub::BadGateway,
      503 => TicketingHub::ServiceUnavailable
    }

    def on_complete response
      key = response[:status].to_i
      raise ERROR_MAP[key].new(response) if ERROR_MAP.has_key? key
    end
  end

  module Connection
    private

      def connection options={}
        token = options.delete(:access_token) || options.delete(:oauth_token) || oauth_token

        options = {
          authenticate: !token.nil?,
          force_urlencoded: false,
          raw: false,
          accept: 'application/json',
          user_agent: user_agent
        }.merge(options)

        options.merge! proxy: proxy unless proxy.nil?

        Faraday.new(options) do |conn|
          conn.request :oauth2, token unless token.nil?
          conn.request options[:force_urlencoded] ? :url_encoded : :json

          conn.use ErrorHandler
          conn.response :follow_redirects
          conn.response :mashify
          conn.response :json, content_type: /\bjson$/
  
          faraday_config_block.call conn if faraday_config_block
          conn.adapter *adapter
        end
      end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
ticketinghub-1.0.3 lib/ticketing_hub/connection.rb
ticketinghub-1.0.2 lib/ticketing_hub/connection.rb
ticketinghub-1.0.1 lib/ticketing_hub/connection.rb