Sha256: ee85198ca83de7461ec0dfa5b78a5c6ff113ecaf3e5650587366ec31678f788d

Contents?: true

Size: 1.32 KB

Versions: 3

Compression:

Stored size: 1.32 KB

Contents

require 'faraday'
require 'json'

module ChatWork
  class Client
    def initialize(api_key, api_base, api_version)
      default_header = {
        'X-ChatWorkToken' => api_key,
        'User-Agent' => "ChatWork#{api_version} RubyBinding/#{ChatWork::VERSION}"
      }

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

    def handle_response(response)
      case response.status
      when 204
        ChatWork::ChatWorkError.from_response(response.status, response.body)
      when 200..299
        begin
          JSON.parse(response.body)
        rescue JSON::ParserError => e
          raise ChatWork::APIConnectionError.new("Response JSON is broken. #{e.message}: #{response.body}", e)
        end
      else
        ChatWork::ChatWorkError.from_response(response.status, response.body)
      end
    end

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

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
chatwork-0.4.1 lib/chatwork/client.rb
chatwork-0.4.0 lib/chatwork/client.rb
chatwork-0.3.1 lib/chatwork/client.rb