Class: Apicraft::Middlewares::RequestValidator

Inherits:
Object
  • Object
show all
Includes:
Concerns::MiddlewareUtil
Defined in:
lib/apicraft/middlewares/request_validator.rb

Overview

Middleware to handle Request Validation.

Instance Method Summary collapse

Methods included from Concerns::MiddlewareUtil

#config, #convertor

Constructor Details

#initialize(app) ⇒ RequestValidator

Returns a new instance of RequestValidator.



9
10
11
# File 'lib/apicraft/middlewares/request_validator.rb', line 9

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/apicraft/middlewares/request_validator.rb', line 13

def call(env)
  return @app.call(env) unless validate?

  request = ActionDispatch::Request.new(env)
  content_type = request.content_type

  operation = Apicraft::Openapi::Contract.find_by_operation(
    request.method, request.path_info
  )&.operation(
    request.method, request.path_info
  )
  return @app.call(env) if operation.blank?

  operation.validate_request_body(
    content_type,
    request.params
  )
  @app.call(env)
rescue OpenAPIParser::OpenAPIError => e
  [
    config.request_validation_http_code,
    { 'Content-Type': content_type },
    [
      response_body(e)&.send(convertor(content_type))
    ].compact
  ]
end