Skip to content
This repository has been archived by the owner on Feb 25, 2023. It is now read-only.

Commit

Permalink
More JSON schema improvements (#729)
Browse files Browse the repository at this point in the history
* Add support for constant values

* Add contains check for arrays

* Add tests

* Simplify getValidValueOrDefault testing
  • Loading branch information
toasted-nutbread authored Aug 11, 2020
1 parent abfa036 commit 587822c
Show file tree
Hide file tree
Showing 2 changed files with 371 additions and 147 deletions.
27 changes: 27 additions & 0 deletions ext/bg/js/json-schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,11 @@ class JsonSchemaValidator {
throw new JsonSchemaValidationError(`Value type ${type} does not match schema type ${schemaType}`, value, schema, info);
}

const schemaConst = schema.const;
if (typeof schemaConst !== 'undefined' && !this.valuesAreEqual(value, schemaConst)) {
throw new JsonSchemaValidationError('Invalid constant value', value, schema, info);
}

const schemaEnum = schema.enum;
if (Array.isArray(schemaEnum) && !this.valuesAreEqualAny(value, schemaEnum)) {
throw new JsonSchemaValidationError('Invalid enum value', value, schema, info);
Expand Down Expand Up @@ -414,6 +419,8 @@ class JsonSchemaValidator {
throw new JsonSchemaValidationError('Array length too long', value, schema, info);
}

this.validateArrayContains(value, schema, info);

for (let i = 0, ii = value.length; i < ii; ++i) {
const schemaPath = [];
const propertySchema = this.getPropertySchema(schema, i, value, schemaPath);
Expand All @@ -431,6 +438,26 @@ class JsonSchemaValidator {
}
}

validateArrayContains(value, schema, info) {
const containsSchema = schema.contains;
if (!this.isObject(containsSchema)) { return; }

info.schemaPush('contains', containsSchema);
for (let i = 0, ii = value.length; i < ii; ++i) {
const propertyValue = value[i];
info.valuePush(i, propertyValue);
try {
this.validate(propertyValue, containsSchema, info);
info.schemaPop();
return;
} catch (e) {
// NOP
}
info.valuePop();
}
throw new JsonSchemaValidationError('contains schema didn\'t match', value, schema, info);
}

validateObject(value, schema, info) {
const properties = new Set(Object.getOwnPropertyNames(value));

Expand Down
Loading

0 comments on commit 587822c

Please sign in to comment.