Class: ApiValve::Forwarder::Request

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

Overview

This class is wraps the original request. It’s methods are called by the Forwarder to make the actual request in the target endpoint. So by changing the public methods in this call, we can control how the request is forwarded

Constant Summary collapse

WHITELISTED_HEADERS =
%w(
  Accept
  Content-Type
  User-Agent
  X-Real-IP
  X-Request-Id
).freeze
NOT_PREFIXED_HEADERS =
%w(
  Content-Length
  Content-Type
).freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(original_request, options = {}) ⇒ Request

Returns a new instance of Request.



22
23
24
25
# File 'lib/api_valve/forwarder/request.rb', line 22

def initialize(original_request, options = {})
  @original_request = original_request
  @options = options.with_indifferent_access
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



8
9
10
# File 'lib/api_valve/forwarder/request.rb', line 8

def options
  @options
end

#original_requestObject (readonly)

Returns the value of attribute original_request.



8
9
10
# File 'lib/api_valve/forwarder/request.rb', line 8

def original_request
  @original_request
end

Instance Method Details

#bodyObject

Returns body to forward to the target endpoint Override to control the payload that is passed through



55
56
57
58
59
# File 'lib/api_valve/forwarder/request.rb', line 55

def body
  return unless %i(put post patch).include? method

  original_request.body.read
end

#headersObject

Returns a hash of headers to forward to the target endpoint Override to control the HTTP headers that will be passed through



47
48
49
50
51
# File 'lib/api_valve/forwarder/request.rb', line 47

def headers
  whitelisted_headers.each_with_object({}) do |key, h|
    h[key] = header(key)
  end.merge(forwarded_headers).compact
end

#methodObject

HTTP method to use when forwarding. Must return sym. Returns original request method



29
30
31
# File 'lib/api_valve/forwarder/request.rb', line 29

def method
  @method ||= original_request.request_method.downcase.to_sym
end

#pathObject

URL path to use when forwarding



34
35
36
37
38
39
40
41
42
43
# File 'lib/api_valve/forwarder/request.rb', line 34

def path
  path = options['endpoint'] || ''
  if (override = override_path(options))
    path += override
  else
    path += original_request.path_info
  end
  # we remove leading slash so we can use endpoints with deeper folder levels
  path.gsub(%r{^/}, '')
end

#url_paramsObject

Returns query params to forward to the target endpoint Override to control the query parameters that can be passed through



63
64
65
66
67
# File 'lib/api_valve/forwarder/request.rb', line 63

def url_params
  return unless original_request.query_string.present?

  @url_params ||= Rack::Utils.parse_nested_query(original_request.query_string)
end