Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Schema validator #52

Open
wants to merge 1 commit into
base: os-17/json-schema-validation
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/jsonapi_parameters.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
require 'jsonapi_parameters/parameters'
require 'jsonapi_parameters/handlers'
require 'jsonapi_parameters/validator'
require 'jsonapi_parameters/schema_validator'
require 'jsonapi_parameters/translator'
require 'jsonapi_parameters/core_ext'
require 'jsonapi_parameters/stack_limit'
Expand Down
51 changes: 51 additions & 0 deletions lib/jsonapi_parameters/schema_validator.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
require 'json_schemer'

module JsonApi::Parameters
SCHEMA_PATH = Pathname.new(__dir__).join('jsonapi_schema.json').to_s.freeze

private

def should_prevalidate?
JsonApi::Parameters.enforce_schema_prevalidation && !JsonApi::Parameters.suppress_schema_validation_errors
end

class SchemaValidator
class ValidationError < StandardError; end

def initialize(payload)
@payload = payload.deep_stringify_keys
end

attr_reader :payload

def validate!
schema = JSONSchemer.schema(File.read(SCHEMA_PATH))

unless schema.valid?(payload) # rubocop:disable Style/GuardClause
errors = []

schema.validate(payload).each do |validation_error|
errors << nice_error(validation_error)
end
Comment on lines +25 to +29
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
errors = []
schema.validate(payload).each do |validation_error|
errors << nice_error(validation_error)
end
errors = schema.validate(payload).map do |validation_error|
nice_error(validation_error)
end

Comment on lines +24 to +29
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

schemer seems not caching validation result so:

Suggested change
unless schema.valid?(payload) # rubocop:disable Style/GuardClause
errors = []
schema.validate(payload).each do |validation_error|
errors << nice_error(validation_error)
end
validation_errors = schema.validate(payload)
unless validation_errors.blank? # rubocop:disable Style/GuardClause
errors = validation_errors.map do |validation_error|
nice_error(validation_error)
end


raise SchemaValidator::ValidationError.new(errors.join(', '))
end
end

private

# Based on & thanks to https://polythematik.de/2020/02/17/ruby-json-schema/
def nice_error(err)
case err['type']
when 'required'
"path '#{err['data_pointer']}' is missing keys: #{err['details']['missing_keys'].join ', '}"
when 'format'
"path '#{err['data_pointer']}' is not in required format (#{err['schema']['format']})"
when 'minLength'
"path '#{err['data_pointer']}' is not long enough (min #{err['schema']['minLength']})"
else
"path '#{err['data_pointer']}' is invalid according to the JsonApi schema"
end
end
end
end
4 changes: 2 additions & 2 deletions lib/jsonapi_parameters/translator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@ def jsonapi_translate(params, naming_convention:)

@jsonapi_unsafe_hash = ensure_naming(params, naming_convention)

JsonApi::Parameters::Validator.new(@jsonapi_unsafe_hash.deep_dup).validate! if should_prevalidate?
JsonApi::Parameters::SchemaValidator.new(@jsonapi_unsafe_hash.deep_dup).validate! if should_prevalidate?

formed_parameters
rescue StandardError => err
# Validate the payload and raise errors...
JsonApi::Parameters::Validator.new(@jsonapi_unsafe_hash.deep_dup).validate! unless JsonApi::Parameters.suppress_schema_validation_errors
JsonApi::Parameters::SchemaValidator.new(@jsonapi_unsafe_hash.deep_dup).validate! unless JsonApi::Parameters.suppress_schema_validation_errors

raise err # ... or if there were none, re-raise initial error
end
Expand Down
52 changes: 0 additions & 52 deletions lib/jsonapi_parameters/validator.rb

This file was deleted.

16 changes: 8 additions & 8 deletions spec/lib/jsonapi_parameters/validator_spec.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
require 'spec_helper'

describe JsonApi::Parameters::Validator do # rubocop:disable RSpec/FilePath
describe JsonApi::Parameters::SchemaValidator do # rubocop:disable RSpec/FilePath
describe 'initializer' do
it 'ensures @payload has keys deeply stringified' do
validator = described_class.new(payload: { sample: 'value' })
Expand All @@ -26,7 +26,7 @@ class Translator
it 'raises validation errors' do
payload = { payload: { sample: 'value' } }

expect { translator.jsonapify(payload) }.to raise_error(ActiveModel::ValidationError)
expect { translator.jsonapify(payload) }.to raise_error(JsonApi::Parameters::SchemaValidator::ValidationError)
end

it 'does not raise TranslatorError' do
Expand All @@ -42,7 +42,7 @@ class Translator

begin
translator.jsonapify(payload)
rescue ActiveModel::ValidationError => _ # rubocop:disable Lint/HandleExceptions
rescue JsonApi::Parameters::SchemaValidator::ValidationError => _ # rubocop:disable Lint/HandleExceptions
end
end
end
Expand All @@ -55,7 +55,7 @@ class Translator
it 'does not raise validation errors' do
payload = { payload: { sample: 'value' } }

expect { translator.jsonapify(payload) }.not_to raise_error(ActiveModel::ValidationError)
expect { translator.jsonapify(payload) }.not_to raise_error(JsonApi::Parameters::SchemaValidator::ValidationError)
end

it 'still raises any other errors' do
Expand All @@ -77,7 +77,7 @@ class Translator
it 'raises validation errors' do
payload = { payload: { sample: 'value' } }

expect { translator.jsonapify(payload) }.to raise_error(ActiveModel::ValidationError)
expect { translator.jsonapify(payload) }.to raise_error(JsonApi::Parameters::SchemaValidator::ValidationError)
end
end

Expand All @@ -88,7 +88,7 @@ class Translator
expect(File).to receive(:read).with(JsonApi::Parameters::SCHEMA_PATH).and_call_original
expect(JSONSchemer).to receive(:schema).and_call_original

expect { validator.validate! }.to raise_error(ActiveModel::ValidationError)
expect { validator.validate! }.to raise_error(JsonApi::Parameters::SchemaValidator::ValidationError)
end
end

Expand All @@ -98,11 +98,11 @@ class Translator
payload = { controller: 'examples_controller', action: 'create', commit: 'Sign up' }
validator = described_class.new(payload)

expect { validator.validate! }.to raise_error(ActiveModel::ValidationError)
expect { validator.validate! }.to raise_error(JsonApi::Parameters::SchemaValidator::ValidationError)

begin
validator.validate!
rescue ActiveModel::ValidationError => err
rescue JsonApi::Parameters::SchemaValidator::ValidationError => err
rails_specific_params.each do |param|
expect(err.message).not_to include("Payload path '/#{param}'")
end
Expand Down