Sha256: 309e18882675fd96a5b88317c67125cfa8e05bed65fcb160c0691e39305f6258

Contents?: true

Size: 1.12 KB

Versions: 1

Compression:

Stored size: 1.12 KB

Contents

# frozen_string_literal: true

require "net/http"
require "json"

module Theone
  # HTTP client to connect to the One API
  class Client
    DEFAULT_ENDPOINT = "https://the-one-api.dev/"
    VERSION = "v2"
    ALLOWED_QUERY_KEYS = %i[page limit offset].freeze

    attr_reader :access_token, :endpoint, :version

    def initialize(access_token:, endpoint: DEFAULT_ENDPOINT, version: VERSION)
      @endpoint = endpoint
      @access_token = access_token
      @version = version
    end

    def api_request(path, query = {})
      query_string = ALLOWED_QUERY_KEYS.intersection(query.keys).map { |k| "#{k}=#{query[k]}" }.join("&")
      uri = URI("#{endpoint}#{version}#{path}?#{query_string}")

      headers = {
        "Authorization" => "Bearer #{access_token}",
        "Content-Type" => "application/json",
        "Accept" => "application/json"
      }

      http = Net::HTTP.new(uri.hostname, uri.port)
      http.use_ssl = uri.instance_of? URI::HTTPS
      res = http.get(uri.request_uri, headers)

      # value (weird name) will raise if the response code is not 200
      res.value
      JSON.parse(res.body)["docs"]
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
juggy-theone-sdk-0.1.1 lib/theone/client.rb