Module: Essential::Client::ClassMethods

Defined in:
lib/essential/client.rb

Instance Method Summary collapse

Instance Method Details

#request(method, url, sid: nil, token: nil, params: {}, headers: {}) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/essential/client.rb', line 6

def request(method, url, sid: nil, token: nil, params: {}, headers: {})
  # GET -> :get, etc
  method = method.to_s.downcase.to_sym

  sid   ||= self.sid
  token ||= self.token

  uri = URI.join(self. api_base, url)

  headers = {
    'Content-Type' => 'application/json',
    'Accept'       => 'application/json',
    'User-Agent'   => user_agent(),
  }.merge(headers || {})

  case method
  when :get, :delete
    uri.query = URI.encode_www_form(params) if params && params.any?
  else
    payload = params.to_json
  end

  opts = {
    method: method,
    url: uri.to_s,
    user: sid,
    password: token,
    timeout: 10,      # TODO config
    open_timeout: 10, # TODO: config
    headers: headers,
    payload: payload
  }

  if $debug
    puts format('%s %s', method.to_s.upcase, uri)
    puts format('opts: %s', JSON.pretty_generate(opts))
  end

  begin
    response = RestClient::Request.execute(opts)
  rescue StandardError => e
    raise Essential::APIError.from_exception(e)
  end

  response
end