Class: DuffelAPI::Request

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

Overview

A class that wraps an API request

Instance Method Summary collapse

Constructor Details

#initialize(connection, method, path, options) ⇒ Request

Initialize a request class, which makes calls to the API

Parameters:

  • connection
  • method (Symbol)

    the method to make the request with

  • path (String)

    the path to make the request to

  • options (hash)

    options for the request

  • headers (hash)

    headers to send with the request



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/duffel_api/request.rb', line 14

def initialize(connection, method, path, options)
  @connection = connection
  @method = method
  @path = path
  @headers = (options.delete(:headers) || {}).transform_keys(&:to_s)
  @given_options = options

  @request_body = request_body

  if @request_body.is_a?(Hash)
    @request_body = @request_body.to_json
    @headers["Content-Type"] ||= "application/json"
  end
end

Instance Method Details

#make_requestObject

Make the API request



35
36
37
38
39
40
41
42
# File 'lib/duffel_api/request.rb', line 35

def make_request
  @connection.send(@method) do |request|
    request.url @path
    request.body = @request_body
    request.params = request_query
    request.headers.merge!(@headers)
  end
end

#requestObject

Make the request and wrap it in a Response object



30
31
32
# File 'lib/duffel_api/request.rb', line 30

def request
  Response.new(make_request)
end

#request_bodyObject

Fetch the body to send with the request



45
46
47
48
49
50
51
52
53
# File 'lib/duffel_api/request.rb', line 45

def request_body
  if @method == :get
    nil
  elsif %i[post put delete patch].include?(@method)
    @given_options.fetch(:params, {})
  else
    raise "Unknown request method #{@method}"
  end
end

#request_queryObject

Get the query params to send with the request



56
57
58
59
60
61
62
# File 'lib/duffel_api/request.rb', line 56

def request_query
  if @method == :get
    @given_options.fetch(:params, {})
  else
    @given_options.fetch(:query_params, {})
  end
end