Class: OpenapiFirst::RequestValidation

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

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of RequestValidation.



13
14
15
16
# File 'lib/openapi_first/request_validation.rb', line 13

def initialize(app, options = {})
  @app = app
  @raise = options.fetch(:raise_error, false)
end

Instance Method Details

#call(env) ⇒ Object

rubocop:disable Metrics/AbcSize



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/openapi_first/request_validation.rb', line 18

def call(env) # rubocop:disable Metrics/AbcSize
  operation = env[OPERATION]
  return @app.call(env) unless operation

  error = catch(:error) do
    query_params = OpenapiParameters::Query.new(operation.query_parameters).unpack(env['QUERY_STRING'])
    validate_query_parameters!(operation, query_params)
    env[PARAMS].merge!(query_params)

    return @app.call(env) unless operation.request_body

    content_type = Rack::Request.new(env).content_type
    validate_request_content_type!(operation, content_type)
    parsed_request_body = env[REQUEST_BODY]
    validate_request_body!(operation, parsed_request_body, content_type)
    nil
  end
  if error
    raise RequestInvalidError, error[:errors] if @raise

    return validation_error_response(error[:status], error[:errors])
  end
  @app.call(env)
end