Class: Uc3DmpId::Validator
- Inherits:
-
Object
- Object
- Uc3DmpId::Validator
- Defined in:
- lib/uc3-dmp-id/validator.rb
Overview
Method that compares incoming JSON against our JSON Schema and provides detailed errors
Constant Summary collapse
- VALIDATION_MODES =
Valid Validation modes are:
- :author --> system of provenance is attempting to create or update - :delete --> system of provenance is attempting to delete/tombstone - :amend --> a non-provenance system is attempting to update
%w[author amend delete].freeze
- MSG_EMPTY_JSON =
'JSON was empty or was not a valid JSON document!'
- MSG_INVALID_JSON =
'Invalid JSON.'
- MSG_NO_SCHEMA =
'No JSON schema available!'
- MSG_BAD_JSON =
'Fatal validation error: %{msg} - %{trace}'
- MSG_VALID_JSON =
'The JSON is valid.'
Class Method Summary collapse
-
._load_schema(mode:) ⇒ Object
Load the JSON schema that corresponds with the mode ————————————————————————————.
-
.validate(mode:, json:) ⇒ Object
Validate the specified DMP’s :json against the schema for the specified :mode rubocop:disable Metrics/AbcSize.
Class Method Details
._load_schema(mode:) ⇒ Object
Load the JSON schema that corresponds with the mode
49 50 51 52 53 54 55 56 57 |
# File 'lib/uc3-dmp-id/validator.rb', line 49 def _load_schema(mode:) # Instatiate the matching schema schema = "Uc3DmpId::Schemas::#{mode.to_s.downcase.capitalize}".split('::').inject(Object) do |o, c| o.const_get c end schema.respond_to?(:load) ? schema.load : nil rescue NameError nil end |
.validate(mode:, json:) ⇒ Object
Validate the specified DMP’s :json against the schema for the specified :mode rubocop:disable Metrics/AbcSize
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/uc3-dmp-id/validator.rb', line 25 def validate(mode:, json:) json = Helper.parse_json(json:) return [MSG_EMPTY_JSON] if json.nil? || !VALIDATION_MODES.include?(mode) # Load the appropriate JSON schema for the mode schema = _load_schema(mode:) return [MSG_NO_SCHEMA] if schema.nil? # Validate the JSON errors = JSON::Validator.fully_validate(schema, json) errors = errors.map { |err| err.gsub('The property \'#/\' ', '') } errors = ([MSG_INVALID_JSON] << errors).flatten.compact.uniq unless errors.empty? errors.map { |err| err.gsub(/in schema [a-z0-9-]+/, '').strip } rescue JSON::Schema::ValidationError => e ["#{MSG_INVALID_JSON} - #{e.}"] end |