Class: Committee::Middleware::Stub

Inherits:
Base
  • Object
show all
Defined in:
lib/committee/middleware/stub.rb

Instance Method Summary collapse

Methods inherited from Base

#call, get_schema

Constructor Details

#initialize(app, options = {}) ⇒ Stub

Returns a new instance of Stub.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/committee/middleware/stub.rb', line 8

def initialize(app, options={})
  super

  # A bug in Committee's cache implementation meant that it wasn't working
  # for a very long time, even for people who thought they were taking
  # advantage of it. I repaired the caching feature, but have disable it by
  # default so that we don't need to introduce any class-level variables
  # that could have memory leaking implications. To enable caching, just
  # pass an empty hash to this option.
  @cache = options[:cache]

  @call = options[:call]

  raise Committee::OpenAPI3Unsupported.new("Stubs are not yet supported for OpenAPI 3") unless @schema.supports_stub?
end

Instance Method Details

#handle(request) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/committee/middleware/stub.rb', line 24

def handle(request)
  link, _ = @router.find_request_link(request)
  if link
    headers = { "Content-Type" => "application/json" }

    data, schema = cache(link) do
      Committee::SchemaValidator::HyperSchema::ResponseGenerator.new.call(link)
    end

    if @call
      request.env["committee.response"] = data
      request.env["committee.response_schema"] = schema
      call_status, call_headers, call_body = @app.call(request.env)

      # a committee.suppress signal initiates a direct pass through
      if request.env["committee.suppress"] == true
        return call_status, call_headers, call_body
      end

      # otherwise keep the headers and whatever data manipulations were
      # made, and stub normally
      headers.merge!(call_headers)

      # allow the handler to change the data object (if unchanged, it
      # will be the same one that we set above)
      data = request.env["committee.response"]
    end

    [link.status_success, headers, [JSON.pretty_generate(data)]]
  else
    @app.call(request.env)
  end
end