Skip to content

Commit

Permalink
Merge pull request #68 from alphagov/ensure-validator-works-with-obje…
Browse files Browse the repository at this point in the history
…ct-or-json-passed-in

Ensure the validator can handle the payload being JSON
  • Loading branch information
davidgisbey authored Jul 22, 2022
2 parents 7abd403 + 72e1e6e commit b658cb2
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 7 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# 4.4.1

* Fix `Validator` module to handle JSON or other object types being passed as the payload ([#68](https://github.com/alphagov/govuk_schemas/pull/68))

# 4.4.0

* Adds support for applications that use Minitest by adding an `AssertMatchers` module ([#66](https://github.com/alphagov/govuk_schemas/pull/66))
Expand Down
17 changes: 11 additions & 6 deletions lib/govuk_schemas/validator.rb
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
module GovukSchemas
class Validator
attr_reader :schema_name, :type, :payload
attr_reader :schema_name, :type
attr_accessor :payload

def initialize(schema_name, type, payload)
@schema_name = schema_name
@type = type
@payload = payload
@payload = ensure_json(payload)
end

def valid?
Expand All @@ -27,20 +28,24 @@ def error_message

def errors
schema = Schema.find("#{type}_schema": schema_name)
validator = JSON::Validator.fully_validate(schema, payload.to_json)
validator = JSON::Validator.fully_validate(schema, payload)
validator.map { |message| "- " + humanized_error(message) }.join("\n")
end

def formatted_payload
return payload if payload.is_a?(String)

JSON.pretty_generate(payload)
JSON.pretty_generate(JSON.parse(payload))
end

def humanized_error(message)
message.gsub("The property '#/'", "The item")
.gsub(/in schema [0-9a-f\-]+/, "")
.strip
end

def ensure_json(payload)
return payload if payload.is_a?(String)

payload.to_json
end
end
end
2 changes: 1 addition & 1 deletion lib/govuk_schemas/version.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module GovukSchemas
# @private
VERSION = "4.4.0".freeze
VERSION = "4.4.1".freeze
end
7 changes: 7 additions & 0 deletions spec/lib/validator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@

expect(validator.valid?).to eq false
end

it "handles the payload being passed as json" do
example = GovukSchemas::RandomExample.for_schema(publisher_schema: "placeholder").to_json
validator = described_class.new("placeholder", "publisher", example)

expect(validator.valid?).to eq true
end
end

describe "#error_message" do
Expand Down

0 comments on commit b658cb2

Please sign in to comment.