Class: OpenapiFirst::Middlewares::RequestValidation

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

Overview

A Rack middleware to validate requests against an OpenAPI API description

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of RequestValidation.

Parameters:

  • app

    The parent Rack application

  • options (defaults to: {})

    An optional Hash of configuration options to override defaults :raise_error A Boolean indicating whether to raise an error if validation fails.

    default: false
    

    :error_response The Class to use for error responses.

    default: OpenapiFirst::Plugins::Default::ErrorResponse (Config.default_options.error_response)
    


14
15
16
17
18
19
20
21
22
23
# File 'lib/openapi_first/middlewares/request_validation.rb', line 14

def initialize(app, options = {})
  @app = app
  @raise = options.fetch(:raise_error, OpenapiFirst.configuration.request_validation_raise_error)
  @error_response_class = error_response(options[:error_response])

  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 Method Details

#call(env) ⇒ Object



25
26
27
28
29
30
31
32
33
34
# File 'lib/openapi_first/middlewares/request_validation.rb', line 25

def call(env)
  request = find_request(env)
  return @app.call(env) unless request

  failure = request.validate
  failure.raise! if failure && @raise
  return @error_response_class.new(failure:).render if failure

  @app.call(env)
end