Class: ActiveCampaignRb::Faraday::Middleware::Request

Inherits:
Faraday::Middleware
  • Object
show all
Includes:
TransformHash
Defined in:
lib/active_campaign_rb/faraday/middleware/request.rb

Overview

Gem specific request middleware for Faraday

Author:

Instance Method Summary collapse

Methods included from TransformHash

transform_array, transform_key, transform_keys, transform_value

Constructor Details

#initialize(app, headers) ⇒ Request

Returns a new instance of Request.



18
19
20
21
# File 'lib/active_campaign_rb/faraday/middleware/request.rb', line 18

def initialize(app, headers)
  super(app)
  @headers = headers
end

Instance Method Details

#call(env) ⇒ Object



23
24
25
26
27
28
29
30
31
32
# File 'lib/active_campaign_rb/faraday/middleware/request.rb', line 23

def call(env)
  case env.method
  when :post, :patch, :put
    normalize_body(env)
  end

  env[:request_headers].merge!(@headers)

  @app.call(env)
end

#loggerObject



49
50
51
# File 'lib/active_campaign_rb/faraday/middleware/request.rb', line 49

def logger
  @logger ||= Logger.new($stdout)
end

#normalize_body(env) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/active_campaign_rb/faraday/middleware/request.rb', line 34

def normalize_body(env)
  body = env[:request_body]
  if body.is_a?(Array)
    body = transform_array(body.flatten, :camelcase, :lower)
  elsif body.key?(:group)
    logger.debug("Using body as is because group #{body}")
  elsif body.key?(:list)
    logger.debug("Using body as is because list #{body}")
  else
    body = transform_keys(body, :camelcase, :lower)
  end

  env[:request_body] = ::Oj.dump(body, mode: :compat)
end