Class: OpenapiFirst::Middlewares::ResponseValidation

Inherits:
Object
  • Object
show all
Defined in:
lib/openapi_first/middlewares/response_validation.rb

Overview

A Rack middleware to validate requests against an OpenAPI API description

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of ResponseValidation.

Parameters:

  • app

    The parent Rack application

  • options (defaults to: {})

    Hash :spec [String, OpenapiFirst::Definition] Path to the OpenAPI file or an instance of Definition :raise_error [Boolean] Whether to raise an error if validation fails. default: true



13
14
15
16
17
18
19
20
21
# File 'lib/openapi_first/middlewares/response_validation.rb', line 13

def initialize(app, options = {})
  @app = app
  @raise = options.fetch(:raise_error, OpenapiFirst.configuration.response_validation_raise_error)

  spec = options.fetch(:spec)
  raise "You have to pass spec: when initializing #{self.class}" unless spec

  @definition = spec.is_a?(Definition) ? spec : OpenapiFirst.load(spec)
end

Instance Attribute Details

#appObject (readonly)



24
25
26
# File 'lib/openapi_first/middlewares/response_validation.rb', line 24

def app
  @app
end

Instance Method Details

#call(env) ⇒ Object



26
27
28
29
30
# File 'lib/openapi_first/middlewares/response_validation.rb', line 26

def call(env)
  status, headers, body = @app.call(env)
  @definition.validate_response(Rack::Request.new(env), Rack::Response[status, headers, body], raise_error: @raise)
  [status, headers, body]
end