Class: Sorry::Api::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/sorry/api/request.rb

Overview

The core requests library, I actually build and make the HTTP requests to the API, parse responses etc.

Instance Method Summary collapse

Constructor Details

#initialize(builder) ⇒ Request

Initialze the request class.



8
9
10
11
12
13
# File 'lib/sorry/api/request.rb', line 8

def initialize(builder)
	# Include the build class which
	# will give us access to the path.
	# TODO: Should we instantiate with this? or make this class methods?
	@request_builder = builder
end

Instance Method Details

#configure_request(request: nil, params: nil) ⇒ Object

Build the request from the givden parameters.



39
40
41
42
43
44
45
46
47
48
# File 'lib/sorry/api/request.rb', line 39

def configure_request(request: nil, params: nil)
				# Set the URL of the request from the compiled path.
				request.url @request_builder.path
				# Marge the parameters into the request.
				request.params.merge!(params) if params
				# Set the request type to JSON.
				request.headers['Content-Type'] = 'application/json'
				# Include the bearer header if one applied as token.
				request.headers['Content-Type']
end

#handle_error(error) ⇒ Object

Handle/Parse an errors which happen.



51
52
53
54
55
# File 'lib/sorry/api/request.rb', line 51

def handle_error(error)
	# Reraise the error for now.
	# TODO: Handler proper errors somehow.
	raise error
end

#http_clientObject

 Get access to the HTTP client to make the request.



65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/sorry/api/request.rb', line 65

def http_client
				# Configure Faraday as our HTTP client.
				Faraday.new(Sorry::Api::ENDPOINT) do |faraday|
# Configure the adapter to throw erros
# based on the HTTP response codes.
faraday.response :raise_error
# Log to the command ling.
faraday.response :logger
# make requests with Net::HTTP
faraday.adapter Faraday.default_adapter
# Set the HTTP oAuth headers.
faraday.authorization :bearer, @request_builder.access_token if @request_builder.access_token
				end
end

#parse_response(response_body) ⇒ Object

Parse the reponse.



58
59
60
61
62
# File 'lib/sorry/api/request.rb', line 58

def parse_response(response_body)
	# Parse the response body from JSON into Hash.
	# Return the enveloped 'response' element.
	MultiJson.load(response_body, :symbolize_keys => true)[:response]
end