Class: JSONSchemer::Rails::OpenApiValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/json_schemer/rails/open_api_validator.rb

Overview

This validates a request against the OpenAPI specification

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(request, open_api_filename: "openapi.yml", ref_resolver: nil) ⇒ OpenApiValidator

Returns a new instance of OpenApiValidator.



10
11
12
13
14
# File 'lib/json_schemer/rails/open_api_validator.rb', line 10

def initialize(request, open_api_filename: "openapi.yml", ref_resolver: nil)
  @request = request
  @open_api_filename = open_api_filename
  @ref_resolver = ref_resolver
end

Instance Attribute Details

#ref_resolverObject (readonly)

Returns the value of attribute ref_resolver.



16
17
18
# File 'lib/json_schemer/rails/open_api_validator.rb', line 16

def ref_resolver
  @ref_resolver
end

#requestObject (readonly)

Returns the value of attribute request.



16
17
18
# File 'lib/json_schemer/rails/open_api_validator.rb', line 16

def request
  @request
end

Instance Method Details

#validate_bodyObject



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/json_schemer/rails/open_api_validator.rb', line 18

def validate_body
  return unless should_validate_body?

  unless request.content_type == "application/json"
    raise RequestValidationError,
          '"Content-Type" request header must be set to "application/json".'
  end

  document.ref("#{request_openapi_path}/requestBody/content/application~1json/schema")
          .validate(JSON.parse(request.body.read))
end

#validated_paramsObject

cast any parameters that are not part of the OpenAPI specification



31
32
33
34
35
36
37
38
39
40
# File 'lib/json_schemer/rails/open_api_validator.rb', line 31

def validated_params
  parameter_specs.each do |spec|
    case spec["in"]
    when "query"
      validate_query_param(spec)
    when "path"
      validate_path_param(spec)
    end
  end
end