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, 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 # @private module Connection private def connection(options={}) options = { authenticate: true, force_urlencoded: false, raw: false, ssl: { verify: false } }.merge(options) options.merge! proxy: proxy unless proxy.nil? # TODO: Don't build on every request Faraday.new(options) do |builder| builder.request options[:force_urlencoded] ? :url_encoded : :json builder.use ErrorHandler builder.use FaradayMiddleware::FollowRedirects builder.use FaradayMiddleware::ParseJson, content_type: /\bjson$/ faraday_config_block.call builder if faraday_config_block builder.adapter *adapter end.tap do |connection| connection.headers[:user_agent] = user_agent connection.basic_auth authentication[:token], authentication[:secret] end end end end