From ae9a20e0de61bbb84ec359004a401d9f2705aeea Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Mon, 30 Nov 2020 18:56:28 -0500 Subject: Json schema improvements (#1078) * Test multipleOf * Refactor defaulting * Use default if invalid for non-object/array properties * Add tests --- ext/bg/js/json-schema.js | 37 ++++++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 15 deletions(-) (limited to 'ext') diff --git a/ext/bg/js/json-schema.js b/ext/bg/js/json-schema.js index ea1531ab..ca5ecd9b 100644 --- a/ext/bg/js/json-schema.js +++ b/ext/bg/js/json-schema.js @@ -594,23 +594,22 @@ class JsonSchemaValidator { return null; } - _getValidValueOrDefault(schema, value, info) { - let type = this._getValueType(value); + _getDefaultSchemaValue(schema) { const schemaType = schema.type; - if (typeof value === 'undefined' || !this._isValueTypeAny(value, type, schemaType)) { - let assignDefault = true; - - const schemaDefault = schema.default; - if (typeof schemaDefault !== 'undefined') { - value = clone(schemaDefault); - type = this._getValueType(value); - assignDefault = !this._isValueTypeAny(value, type, schemaType); - } + const schemaDefault = schema.default; + return ( + typeof schemaDefault !== 'undefined' && + this._isValueTypeAny(schemaDefault, this._getValueType(schemaDefault), schemaType) ? + clone(schemaDefault) : + this._getDefaultTypeValue(schemaType) + ); + } - if (assignDefault) { - value = this._getDefaultTypeValue(schemaType); - type = this._getValueType(value); - } + _getValidValueOrDefault(schema, value, info) { + let type = this._getValueType(value); + if (typeof value === 'undefined' || !this._isValueTypeAny(value, type, schema.type)) { + value = this._getDefaultSchemaValue(schema); + type = this._getValueType(value); } switch (type) { @@ -620,6 +619,14 @@ class JsonSchemaValidator { case 'array': value = this._populateArrayDefaults(value, schema, info); break; + default: + if (!this.isValid(value, schema)) { + const schemaDefault = this._getDefaultSchemaValue(schema); + if (this.isValid(schemaDefault, schema)) { + value = schemaDefault; + } + } + break; } return value; -- cgit v1.2.3