import { TJS, AJV } from '../common'; /** * A JSON schema for 1..n types. */ export class SchemaDefinition { public readonly types: string[]; public readonly def: TJS.Definition; private _isValidSchema: boolean; private _validator: AJV.ValidateFunction; constructor(args: { type: string | string[]; def: TJS.Definition }) { this.types = Array.isArray(args.type) ? args.type : [args.type]; this.def = args.def; } /** * Determines whether the schema itself is valid. */ public get isValidSchema() { if (this._isValidSchema === undefined) { const ajv = AJV(); this._isValidSchema = ajv.validateSchema(this.def); } return this._isValidSchema; } /** * Retrieves the version of JSON-schema. */ public get schemaVersion() { return this.def.$schema; } /** * Validates the given data against the schema. */ public validate(data: object) { return this.validator(data); } /** * INTERNAL */ private get validator() { if (!this._validator) { const ajv = AJV(); this._validator = ajv.compile(this.def); } return this._validator; } }