Class: OpenapiFirst::Validators::RequestBody

Inherits:
Object
  • Object
show all
Defined in:
lib/openapi_first/validators/request_body.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema, required:) ⇒ RequestBody

Returns a new instance of RequestBody.



16
17
18
19
# File 'lib/openapi_first/validators/request_body.rb', line 16

def initialize(schema, required:)
  @schema = schema
  @required = required
end

Class Method Details

.for(request_definition, openapi_version:, hooks: {}) ⇒ Object



6
7
8
9
10
11
12
13
14
# File 'lib/openapi_first/validators/request_body.rb', line 6

def self.for(request_definition, openapi_version:, hooks: {})
  schema = request_definition.content_schema
  return unless schema

  after_property_validation = hooks[:after_request_body_property_validation]

  new(Schema.new(schema, after_property_validation:, openapi_version:),
      required: request_definition.required_request_body?)
end

Instance Method Details

#call(request) ⇒ Object



21
22
23
24
25
26
27
28
29
30
# File 'lib/openapi_first/validators/request_body.rb', line 21

def call(request)
  request_body = read_body(request)
  if request_body.nil?
    Failure.fail!(:invalid_body, message: 'Request body is not defined') if @required
    return
  end

  validation = @schema.validate(request_body)
  Failure.fail!(:invalid_body, errors: validation.errors) if validation.error?
end