summaryrefslogtreecommitdiff
path: root/dev/schema-validate.js
diff options
context:
space:
mode:
authortoasted-nutbread <toasted-nutbread@users.noreply.github.com>2023-11-29 20:13:15 -0500
committertoasted-nutbread <toasted-nutbread@users.noreply.github.com>2023-11-29 20:13:15 -0500
commite215656ce9b965360e540da93ebf5c381cbe4e41 (patch)
tree4937ca040460d775472f1f3ce1bb179af7b0b661 /dev/schema-validate.js
parentec67de5c0c4abc11232d3f3a8a8e9bb2fe045daa (diff)
Update types
Diffstat (limited to 'dev/schema-validate.js')
-rw-r--r--dev/schema-validate.js25
1 files changed, 21 insertions, 4 deletions
diff --git a/dev/schema-validate.js b/dev/schema-validate.js
index fbd6b06a..a1fe8455 100644
--- a/dev/schema-validate.js
+++ b/dev/schema-validate.js
@@ -17,31 +17,48 @@
*/
import Ajv from 'ajv';
+import {readFileSync} from 'fs';
import {JsonSchema} from '../ext/js/data/json-schema.js';
+import {DataError} from './data-error.js';
class JsonSchemaAjv {
+ /**
+ * @param {import('dev/schema-validate').Schema} schema
+ */
constructor(schema) {
const ajv = new Ajv({
meta: false,
strictTuples: false,
allowUnionTypes: true
});
- ajv.addMetaSchema(require('ajv/dist/refs/json-schema-draft-07.json'));
- this._validate = ajv.compile(schema);
+ const metaSchemaPath = require.resolve('ajv/dist/refs/json-schema-draft-07.json');
+ const metaSchema = JSON.parse(readFileSync(metaSchemaPath, {encoding: 'utf8'}));
+ ajv.addMetaSchema(metaSchema);
+ /** @type {import('ajv').ValidateFunction} */
+ this._validate = ajv.compile(/** @type {import('ajv').Schema} */ (schema));
}
+ /**
+ * @param {unknown} data
+ * @throws {Error}
+ */
validate(data) {
if (this._validate(data)) { return; }
const {errors} = this._validate;
- const error = new Error('Schema validation failed');
+ const error = new DataError('Schema validation failed');
error.data = JSON.parse(JSON.stringify(errors));
throw error;
}
}
+/**
+ * @param {import('dev/schema-validate').ValidateMode} mode
+ * @param {import('dev/schema-validate').Schema} schema
+ * @returns {JsonSchema|JsonSchemaAjv}
+ */
export function createJsonSchema(mode, schema) {
switch (mode) {
case 'ajv': return new JsonSchemaAjv(schema);
- default: return new JsonSchema(schema);
+ default: return new JsonSchema(/** @type {import('json-schema').Schema} */ (schema));
}
}