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, spec = nil, options = {}) ⇒ RequestValidation

Returns a new instance of RequestValidation.

Parameters:

  • app

    The parent Rack application

  • spec (String, OpenapiFirst::Definition) (defaults to: nil)

    Path to the OpenAPI file or an instance of Definition.

  • options (defaults to: {})

    Hash :spec [String, OpenapiFirst::Definition] Path to the OpenAPI file or an instance of Definition.

    This will be deprecated. Please use spec argument instead.
    

    :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)
    


19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/openapi_first/middlewares/request_validation.rb', line 19

def initialize(app, spec = nil, options = {})
  @app = app
  if spec.is_a?(Hash)
    options = spec
    spec = options.fetch(:spec)
  end
  @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)



35
36
37
# File 'lib/openapi_first/middlewares/request_validation.rb', line 35

def app
  @app
end

Instance Method Details

#call(env) ⇒ Object



37
38
39
40
41
42
43
44
# File 'lib/openapi_first/middlewares/request_validation.rb', line 37

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