Class: OpenapiFirst::Schema

Inherits:
Object
  • Object
show all
Defined in:
lib/openapi_first/schema.rb,
lib/openapi_first/schema/validation_error.rb,
lib/openapi_first/schema/validation_result.rb

Overview

Validate data via JSON Schema. A wrapper around JSONSchemer.

Defined Under Namespace

Classes: ValidationResult

Constant Summary collapse

SCHEMAS =
{
  '3.1' => 'https://spec.openapis.org/oas/3.1/dialect/base',
  '3.0' => 'json-schemer://openapi30/schema'
}.freeze
ValidationError =

One of multiple validation errors. Returned by Schema::ValidationResult#errors.

Data.define(:message, :data_pointer, :schema_pointer, :type, :details) do
  # @deprecated Please use {#message} instead
  def error
    warn 'OpenapiFirst::Schema::ValidationError#error is deprecated. Use #message instead.'
    message
  end

  # @deprecated Please use {#data_pointer} instead
  def instance_location
    warn 'OpenapiFirst::Schema::ValidationError#instance_location is deprecated. Use #data_pointer instead.'
    data_pointer
  end

  # @deprecated Please use {#schema_pointer} instead
  def schema_location
    warn 'OpenapiFirst::Schema::ValidationError#schema_location is deprecated. Use #schema_pointer instead.'
    schema_pointer
  end
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema, openapi_version: '3.1', write: true, after_property_validation: nil) ⇒ Schema

Returns a new instance of Schema.



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/openapi_first/schema.rb', line 16

def initialize(schema, openapi_version: '3.1', write: true, after_property_validation: nil)
  @schemer = JSONSchemer.schema(
    schema,
    access_mode: write ? 'write' : 'read',
    meta_schema: SCHEMAS.fetch(openapi_version),
    insert_property_defaults: true,
    output_format: 'classic',
    before_property_validation: method(:before_property_validation),
    after_property_validation:
  )
end

Instance Attribute Details

#schemaObject (readonly)

Returns the value of attribute schema.



9
10
11
# File 'lib/openapi_first/schema.rb', line 9

def schema
  @schema
end

Instance Method Details

#validate(data) ⇒ Object



28
29
30
# File 'lib/openapi_first/schema.rb', line 28

def validate(data)
  ValidationResult.new(@schemer.validate(data))
end