Class: LearnWorlds::Resource

Inherits:
Object
  • Object
show all
Defined in:
lib/learn_worlds/resource.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client) ⇒ Resource

Returns a new instance of Resource.



5
6
7
# File 'lib/learn_worlds/resource.rb', line 5

def initialize(client)
  @client = client
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



3
4
5
# File 'lib/learn_worlds/resource.rb', line 3

def client
  @client
end

Instance Method Details

#default_headersObject



49
50
51
52
53
54
# File 'lib/learn_worlds/resource.rb', line 49

def default_headers
  headers = { 'Lw-Client': client.client_id }
  headers.merge!({ Authorization: "Bearer #{client.access_token}" }) if client.access_token

  headers
end

#delete_request(url, params = {}, headers = {}) ⇒ Object



25
26
27
# File 'lib/learn_worlds/resource.rb', line 25

def delete_request(url, params = {}, headers = {})
  handle_response client.connection.delete(url, params, default_headers.merge(headers))
end

#get_request(url, params = {}, headers = {}) ⇒ Object



9
10
11
# File 'lib/learn_worlds/resource.rb', line 9

def get_request(url, params = {}, headers = {})
  handle_response client.connection.get(url, params, default_headers.merge(headers))
end

#handle_errors(response_body) ⇒ Object

Raises:



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/learn_worlds/resource.rb', line 37

def handle_errors(response_body)
  error = response_body["errors"]&.first || {}

  error_message = error["message"] || response_body["error"]
  error_context = error["context"]
  error_code = error["code"]

  return if error_message.nil?

  raise LearnWorldsError.new(message: error_message, context: error_context, code: error_code)
end

#handle_response(response) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/learn_worlds/resource.rb', line 29

def handle_response(response)
  response_body = response.body
  response_body = JSON.parse(response_body) if response_body.instance_of?(String)
  handle_errors(response_body)

  response
end

#patch_request(url, body = {}, headers = {}) ⇒ Object



17
18
19
# File 'lib/learn_worlds/resource.rb', line 17

def patch_request(url, body = {}, headers = {})
  handle_response client.connection.patch(url, body, default_headers.merge(headers))
end

#post_request(url, body = {}, headers = {}) ⇒ Object



13
14
15
# File 'lib/learn_worlds/resource.rb', line 13

def post_request(url, body = {}, headers = {})
  handle_response client.connection.post(url, body, default_headers.merge(headers))
end

#put_request(url, body = {}, headers = {}) ⇒ Object



21
22
23
# File 'lib/learn_worlds/resource.rb', line 21

def put_request(url, body = {}, headers = {})
  handle_response client.connection.put(url, body, default_headers.merge(headers))
end