Class: OpenapiFirst::RequestValidation

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

Overview

A Rack middleware to validate requests against an OpenAPI API description

Class Method 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 :error_response A Boolean indicating whether to raise an error if validation fails.

    default: OpenapiFirst::ErrorResponses::Default (Config.default_options.error_response)
    

    :raise_error The Class to use for error responses.

    default: false (Config.default_options.request_validation_raise_error)
    


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

def initialize(app, options = {})
  @app = app
  @raise = options.fetch(:raise_error, Config.default_options.request_validation_raise_error)
  @error_response_class =
    Plugins.find_error_response(options.fetch(:error_response, Config.default_options.error_response))
end

Class Method Details

.fail!(status, location, schema_validation: nil) ⇒ Object

Parameters:

  • status (Integer)

    The intended HTTP status code (usually 400)

  • location (Symbol)

    One of :body, :header, :cookie, :query, :path

  • schema_validation (OpenapiFirst::JsonSchema::Result) (defaults to: nil)


23
24
25
26
27
28
29
# File 'lib/openapi_first/request_validation.rb', line 23

def self.fail!(status, location, schema_validation: nil)
  throw FAIL, RequestValidationError.new(
    status:,
    location:,
    schema_validation:
  )
end

Instance Method Details

#call(env) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/openapi_first/request_validation.rb', line 44

def call(env)
  operation = env[OPERATION]
  return @app.call(env) unless operation

  error = validate_request(operation, env)
  if error
    raise RequestInvalidError, error.error_message if @raise

    return @error_response_class.new(env, error).render
  end
  @app.call(env)
end