@mojojs/core
Version:
Real-time web framework
47 lines • 1.42 kB
JavaScript
import { ValidatorResult } from './validator/result.js';
import Ajv from 'ajv';
/**
* JSON schema validator class.
*/
export class Validator {
constructor() {
this._ajv = new Ajv({ coerceTypes: 'array' });
}
/**
* Add JSON schema.
*/
addSchema(schema, name) {
this._ajv.addSchema(schema, name);
}
/**
* Get JSON schema validation function.
*/
schema(schema) {
const ajv = this._ajv;
let validate;
if (typeof schema === 'string') {
validate = ajv.getSchema(schema);
}
else if (schema.$id !== undefined) {
if ((validate = ajv.getSchema(schema.$id)) === undefined)
validate = ajv.compile(schema);
}
else {
validate = ajv.compile(schema);
}
if (validate === undefined)
throw new Error(`Invalid schema: ${schema}`);
return function (data) {
const isValid = validate(data);
const errors = [];
const results = validate.errors;
if (results != null) {
for (const error of results) {
errors.push({ instancePath: error.instancePath, schemaPath: error.schemaPath, message: error.message });
}
}
return new ValidatorResult(isValid, errors);
};
}
}
//# sourceMappingURL=validator.js.map