Sha256: 8c64fa8a3678b711257d41c4b72a9bb3eb85ab3283708e58fb0231d17f8c89b2

Contents?: true

Size: 1.24 KB

Versions: 3

Compression:

Stored size: 1.24 KB

Contents

require "faraday"
require "faraday_middleware"

module ChatWork
  class BaseClient
    def initialize(api_base, api_version, header)
      default_header = {
        "User-Agent" => "ChatWork#{api_version} RubyBinding/#{ChatWork::VERSION}",
      }

      default_header.merge!(header)

      @conn = Faraday.new("#{api_base}#{api_version}", headers: default_header) do |builder|
        builder.request :url_encoded
        builder.response :mashify
        builder.response :json
        builder.adapter Faraday.default_adapter
      end
      @api_version = api_version
    end

    def handle_response(response)
      case response.status
      when 200..299
        response.body
      else
        raise ChatWork::ChatWorkError.from_response(response.status, response.body, response.headers)
      end
    end

    Faraday::Connection::METHODS.each do |method|
      define_method(method) do |url, *args, &block|
        begin
          response = @conn.__send__(method, @api_version + url, *args)
        rescue Faraday::Error::ClientError => e
          raise ChatWork::APIConnectionError.faraday_error(e)
        end
        payload = handle_response(response)
        block.call(payload, response.headers) if block
        payload
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
chatwork-0.7.0 lib/chatwork/base_client.rb
chatwork-0.6.2 lib/chatwork/base_client.rb
chatwork-0.6.1 lib/chatwork/base_client.rb