Sha256: 3f25eddff78389351351487fc1dc864fb947410f818078f842b2be824ab127a8

Contents?: true

Size: 1.72 KB

Versions: 1

Compression:

Stored size: 1.72 KB

Contents

module DesignHuddle
  class Client
    attr_accessor :subdomain, :client_id, :access_token

    def initialize(subdomain:nil, client_id: nil, client_secret: nil)
      @subdomain = subdomain || ENV["DESIGN_HUDDLE_SUBDOMAIN"]
      @client_id = client_id || ENV["DESIGN_HUDDLE_CLIENT_ID"]
      @client_secret = client_secret || ENV["DESIGN_HUDDLE_CLIENT_SECRET"]
      request_access_token
      self
    end

    def request_access_token
      RestClient::Request.execute(
        method: :post,
        url: "https://#{subdomain}.designhuddle.com/oauth/token",
        payload: {
          grant_type: "client_credentials",
          client_id: client_id,
          client_secret: @client_secret
        },
        headers: {
          "Content-Type" => "application/x-www-form-urlencoded"
        }
      ) do |response, _request, _result|
        case response.code
        when 200
          self.access_token = JSON.parse(response.body)["access_token"]
        else
          raise "Error: #{response.code} #{response.body}"
        end
      end
    end

    def call(method: :get, path: nil, url: nil, payload: nil, headers: {})
      response = RestClient::Request.execute(
        method: method,
        url: url || "https://#{subdomain}.designhuddle.com#{path}",
        payload: payload,
        headers: {
          Authorization: "Bearer #{access_token}",
          "Content-Type" => "application/json",
          "Accept" => "application/json"
        }.merge(headers)
      ) do |response, _request, _result|
        case response.code
        when 200..399
          response.body.empty? ? response : JSON.parse(response.body)
        else
          raise "Error: #{response.code} #{response.body}"
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
design_huddle-0.1.0 lib/design_huddle/client.rb