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