UNPKG

@furystack/rest-service

Version:

Repository implementation for FuryStack

32 lines 1.1 kB
import Ajv from 'ajv'; import useFormats from 'ajv-formats'; import { SchemaValidationError } from './schema-validation-error.js'; export class SchemaValidator { schema; ajv; constructor(schema, ajvOptions) { this.schema = schema; this.ajv = new Ajv.default({ allErrors: true, ...ajvOptions, }); useFormats.default(this.ajv); } /** * @param data The object to validate * @param options Options for the schema validation * @param options.schemaName The name of the type in the Schema Definitions * @throws SchemaValidationError when the validation has been failed * @returns true in case of validation success */ isValid(data, options) { const schema = { ...this.schema, $ref: `#/definitions/${options.schemaName}` }; const validatorFn = this.ajv.compile(schema); const isValid = validatorFn(data); if (!isValid) { throw new SchemaValidationError(validatorFn.errors); } return true; } } //# sourceMappingURL=schema-validator.js.map