Sha256: b262f2ed5d6492530e62795e3c0dbc38710ff8946cc24f8c53e88bfa35b40fd1

Contents?: true

Size: 1.56 KB

Versions: 8

Compression:

Stored size: 1.56 KB

Contents

require "faraday"

module Paddle
  class Client
    class << self
      def connection
        @connection ||= create_connection
      end

      def get_request(url, params: {}, headers: {})
        handle_response(connection.get(url, params, headers))
      end

      def post_request(url, body: {}, headers: {})
        handle_response(connection.post(url, body, headers))
      end

      def patch_request(url, body:, headers: {})
        handle_response(connection.patch(url, body, headers))
      end

      def delete_request(url, headers: {})
        handle_response(connection.delete(url, headers))
      end

      private

      def create_connection
        Faraday.new(Paddle.config.url) do |conn|
          conn.request :authorization, :Bearer, Paddle.config.api_key
          conn.headers = default_headers
          conn.request :json
          conn.response :json
        end
      end

      def default_headers
        {
          "User-Agent" => "paddle/v#{VERSION} (github.com/deanpcmad/paddle)",
          "Paddle-Version" => Paddle.config.version.to_s
        }
      end

      def handle_response(response)
        return true if response.status == 204
        return response unless error?(response)

        raise_error(response)
      end

      def error?(response)
        [ 400, 401, 403, 404, 409, 429, 500, 501, 503 ].include?(response.status) ||
          response.body&.key?("error")
      end

      def raise_error(response)
        error = Paddle::ErrorFactory.create(response.body, response.status)
        raise error if error
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
paddle-2.7.0 lib/paddle/client.rb
paddle-2.6.0 lib/paddle/client.rb
paddle-2.5.2 lib/paddle/client.rb
paddle-2.5.1 lib/paddle/client.rb
paddle-2.5.0 lib/paddle/client.rb
paddle-2.4.1 lib/paddle/client.rb
paddle-2.4.0 lib/paddle/client.rb
paddle-2.3.0 lib/paddle/client.rb