UNPKG

1.15 kBPlain TextView Raw
1import { TJS, AJV } from '../common';
2
3/**
4 * A JSON schema for 1..n types.
5 */
6export class SchemaDefinition {
7 public readonly types: string[];
8 public readonly def: TJS.Definition;
9
10 private _isValidSchema: boolean;
11 private _validator: AJV.ValidateFunction;
12
13 constructor(args: { type: string | string[]; def: TJS.Definition }) {
14 this.types = Array.isArray(args.type) ? args.type : [args.type];
15 this.def = args.def;
16 }
17
18 /**
19 * Determines whether the schema itself is valid.
20 */
21 public get isValidSchema() {
22 if (this._isValidSchema === undefined) {
23 const ajv = AJV();
24 this._isValidSchema = ajv.validateSchema(this.def);
25 }
26 return this._isValidSchema;
27 }
28
29 /**
30 * Retrieves the version of JSON-schema.
31 */
32 public get schemaVersion() {
33 return this.def.$schema;
34 }
35
36 /**
37 * Validates the given data against the schema.
38 */
39 public validate(data: object) {
40 return this.validator(data);
41 }
42
43 /**
44 * INTERNAL
45 */
46 private get validator() {
47 if (!this._validator) {
48 const ajv = AJV();
49 this._validator = ajv.compile(this.def);
50 }
51 return this._validator;
52 }
53}