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 Attribute Summary collapse

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.

    This can be a Symbol-name of an registered error response (:default, :jsonapi)
    or it can be set to false to disable returning a response.
    default: OpenapiFirst::Plugins::Default::ErrorResponse (Config.default_options.error_response)
    


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

def initialize(app, options = {})
  @app = app
  @raise = options.fetch(:raise_error, OpenapiFirst.configuration.request_validation_raise_error)
  @error_response_class = error_response_option(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 Attribute Details

#appObject (readonly)



28
29
30
# File 'lib/openapi_first/middlewares/request_validation.rb', line 28

def app
  @app
end

Instance Method Details

#call(env) ⇒ Object



30
31
32
33
34
35
36
37
# File 'lib/openapi_first/middlewares/request_validation.rb', line 30

def call(env)
  validated = @definition.validate_request(Rack::Request.new(env), raise_error: @raise)
  env[REQUEST] = validated
  failure = validated.error
  return @error_response_class.new(failure:).render if failure && @error_response_class

  @app.call(env)
end