Files
openstapps/packages/core-validator/src/index.js

63 lines
1.5 KiB
JavaScript

import Ajv from 'ajv';
import addFormats from 'ajv-formats';
import schema from '@openstapps/core/schema.json' assert {type: 'json'};
/**
* StAppsCore validator
* @typedef {import('ajv').AnySchema} AnySchema
* @typedef {import('@openstapps/core/schema.json').SchemaMap} SchemaMap
*/
export class Validator {
/**
* @private
* @readonly
* @type {Ajv.default}
*/
ajv;
get errors() {
return this.ajv.errors;
}
/**
* @param additionalSchemas {AnySchema[]}
*/
constructor(additionalSchemas = []) {
this.ajv = new Ajv.default({
schemas: [schema, ...additionalSchemas],
verbose: true,
keywords: ['elasticsearch'],
allowUnionTypes: true,
});
addFormats.default(this.ajv, {
formats: ['date-time', 'time', 'uuid', 'duration'],
mode: 'fast',
});
}
/**
* Add additional schemas to the validator
* @param schema {AnySchema[]}
*/
addSchema(...schema) {
this.ajv.addSchema(schema);
}
/**
* Validates anything against a given schema name or infers schema name from object
* @template {SchemaMap[keyof SchemaMap]} T
*
* @param instance {unknown} Instance to validate
* @param schema {import('./types.js').NameOf<T>} Name of schema to validate instance against or the schema itself
* @returns {instance is T}
*
*/ /**
* @param instance {unknown}
* @param schema {Ajv.Schema | string}
* @returns {boolean}
*/
validate(instance, schema) {
return this.ajv.validate(typeof schema === 'string' ? `#/definitions/${schema}` : schema, instance);
}
}