diff options
author | Darius Jahandarie <djahandarie@gmail.com> | 2023-12-06 03:53:16 +0000 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-12-06 03:53:16 +0000 |
commit | bd5bc1a5db29903bc098995cd9262c4576bf76af (patch) | |
tree | c9214189e0214480fcf6539ad1c6327aef6cbd1c /dev/schema-validate.js | |
parent | fd6bba8a2a869eaf2b2c1fa49001f933fce3c618 (diff) | |
parent | 23e6fb76319c9ed7c9bcdc3efba39bc5dd38f288 (diff) |
Merge pull request #339 from toasted-nutbread/type-annotations
Type annotations
Diffstat (limited to 'dev/schema-validate.js')
-rw-r--r-- | dev/schema-validate.js | 25 |
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)); } } |