Sha256: a73e6e918c9527e43d87f3460a44cdbc74a72c1c0898dac095b2d6682e26bcb4

Contents?: true

Size: 1.33 KB

Versions: 4

Compression:

Stored size: 1.33 KB

Contents

# frozen_string_literal: true

require "faraday"
require "oj"

module WhatsappSdk
  module Api
    class Client
      API_VERSION = "v14.0"
      API_CLIENT = "https://graph.facebook.com/#{API_VERSION}/"

      def initialize(access_token)
        @access_token = access_token
      end

      def send_request(endpoint: "", full_url: nil, http_method: "post", params: {})
        url = full_url || API_CLIENT

        response = faraday(url).public_send(http_method, endpoint, params)
        Oj.load(response.body)
      end

      def download_file(url, path_to_file_name = nil)
        uri = URI.parse(url)
        request = Net::HTTP::Get.new(uri)
        request["Authorization"] = "Bearer #{@access_token}"
        req_options = { use_ssl: uri.scheme == "https" }

        response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
          http.request(request)
        end

        File.write(path_to_file_name, response.body) if response.code == "200" && path_to_file_name

        response
      end

      private

      def faraday(url)
        ::Faraday.new(url) do |client|
          client.request :multipart
          client.request :url_encoded
          client.adapter ::Faraday.default_adapter
          client.headers['Authorization'] = "Bearer #{@access_token}" unless @access_token.nil?
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
whatsapp_sdk-0.3.2 lib/whatsapp_sdk/api/client.rb
whatsapp_sdk-0.3.1 lib/whatsapp_sdk/api/client.rb
whatsapp_sdk-0.3.0 lib/whatsapp_sdk/api/client.rb
whatsapp_sdk-0.2.0 lib/whatsapp_sdk/api/client.rb