Module: OpenapiContracts::Validators::SchemaValidation

Included in:
RequestBody, ResponseBody
Defined in:
lib/openapi_contracts/validators/schema_validation.rb

Class Method Summary collapse

Class Method Details

.build_validation_schema(schema) ⇒ Object



5
6
7
8
9
10
# File 'lib/openapi_contracts/validators/schema_validation.rb', line 5

def build_validation_schema(schema)
  schema.raw.merge(
    '$ref'    => schema.fragment,
    '$schema' => schema_draft_version(schema)
  )
end

.error_to_message(error) ⇒ Object



12
13
14
15
16
17
18
19
20
21
# File 'lib/openapi_contracts/validators/schema_validation.rb', line 12

def error_to_message(error)
  pointer = " at #{error['data_pointer']}" if error['data_pointer'].present?
  if error.key?('details')
    error['details'].to_a.map { |(key, val)|
      "#{key.humanize}: #{val}#{pointer}"
    }.to_sentence
  else
    "#{error['data'].inspect}#{pointer} does not match the schema"
  end
end

.schema_draft_version(schema) ⇒ Object



23
24
25
26
27
28
29
30
31
# File 'lib/openapi_contracts/validators/schema_validation.rb', line 23

def schema_draft_version(schema)
  if schema.openapi_version.blank? || schema.openapi_version < Gem::Version.new('3.1')
    # Closest compatible version is actually draft 5 but not supported by json-schemer
    'http://json-schema.org/draft-04/schema#'
  else
    # >= 3.1 is actually comptable with 2020-12 but not yet supported by json-schemer
    'http://json-schema.org/draft-07/schema#'
  end
end

.validate_schema(schema, data) ⇒ Object



33
34
35
36
37
38
# File 'lib/openapi_contracts/validators/schema_validation.rb', line 33

def validate_schema(schema, data)
  schemer = JSONSchemer.schema(build_validation_schema(schema))
  schemer.validate(data).map do |err|
    error_to_message(err)
  end
end