Sha256: 7b0a55b08f3f3a153c15a10fec422c241d16c68e060d7cf8adeb788ad9e44946

Contents?: true

Size: 1.32 KB

Versions: 7

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}")
        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

7 entries across 7 versions & 1 rubygems

Version Path
chatwork-0.3.0 lib/chatwork/client.rb
chatwork-0.2.0 lib/chatwork/client.rb
chatwork-0.1.2 lib/chatwork/client.rb
chatwork-0.1.1 lib/chatwork/client.rb
chatwork-0.1.0 lib/chatwork/client.rb
chatwork-0.0.7 lib/chatwork/client.rb
chatwork-0.0.6 lib/chatwork/client.rb