Class: Apicraft::Middlewares::Mocker

Inherits:
Object
  • Object
show all
Includes:
Concerns::MiddlewareUtil
Defined in:
lib/apicraft/middlewares/mocker.rb

Overview

Apicraft Middleware to handle routing and make mock calls available.

Instance Method Summary collapse

Methods included from Concerns::MiddlewareUtil

#config, #convertor

Constructor Details

#initialize(app) ⇒ Mocker

Returns a new instance of Mocker.



10
11
12
# File 'lib/apicraft/middlewares/mocker.rb', line 10

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/apicraft/middlewares/mocker.rb', line 14

def call(env)
  return @app.call(env) unless config.mocks

  request = ActionDispatch::Request.new(env)
  return @app.call(env) unless mock?(request)

  use_delay!(request)
  contract = find_contract!(request)
  operation = find_operation!(contract, request)

  code = request.headers[config.headers[:response_code]] || "200"
  response = operation.response_for(code.to_s)
  raise Errors::InvalidResponse if response.blank?

  content, content_type = response.mock(request.content_type)

  [
    code.to_i,
    {
      'Content-Type': content_type
    },
    [
      content&.send(convertor(content_type))
    ].compact
  ]
end