aboutsummaryrefslogtreecommitdiff
path: root/dev/schema-validate.js
diff options
context:
space:
mode:
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));
}
}