Sha256: d436160953333e6e0bb52ff657f95068fc3fcf92b5116ebf3f95f50a82d03ccb

Contents?: true

Size: 1.4 KB

Versions: 2

Compression:

Stored size: 1.4 KB

Contents

# frozen_string_literal: true

module FreshchatWhatsapp
  class Client
    def initialize(token_type = :bearer)
      @base_path = FreshchatWhatsapp.configuration.base_path
      @token = FreshchatWhatsapp.configuration.api_key
      @token_type = token_type
    end

    def request(path, payload = nil)
      full_path = "#{base_path}#{path}"
      conn = Faraday.new(url: full_path, headers: headers)
      response = conn.post { |request| request.body = body(payload) }

      unless response.success?
        raise FreshchatWhatsapp::Errors::RequestError.new('FreshchatWhatsapp API request error.', response.body)
      end

      JSON.parse(response.body)
    end

    def get_request(path, payload = nil)
      full_path = "#{base_path}#{path}"
      conn = Faraday.new(url: full_path, headers: headers)
      response = conn.get { |request| request.body = body(payload) }

      unless response.success?
        raise FreshchatWhatsapp::Errors::RequestError.new('FreshchatWhatsapp API request error.', response.body)
      end

      JSON.parse(response.body)
    end

    private

    attr_reader :base_path, :token, :token_type

    def token_name
      case token_type
      when :bearer
        'Bearer'
      end
    end

    def headers
      {
        'Authorization' => "#{token_name} #{token}",
        'Content-Type' => 'application/json'
      }
    end

    def body(payload)
      payload&.to_json
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
freshchat_whatsapp-0.1.1 lib/freshchat_whatsapp/client.rb
freshchat_whatsapp-0.1.0 lib/freshchat_whatsapp/client.rb