UNPKG

2.53 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const lodash_1 = require("lodash");
4const AjvCtor = require("ajv");
5class ValidationError extends Error {
6 constructor(message, errors) {
7 super(message);
8 this.errors = errors;
9 this.name = 'ValidationError';
10 }
11}
12exports.ValidationError = ValidationError;
13function createValidator() {
14 const ajv = new AjvCtor({ useDefaults: true, allErrors: true });
15 ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'));
16 ajv.addKeyword('coerce-date', {
17 type: 'string',
18 modifying: true,
19 valid: true,
20 compile: (onOrOff, parentSchema) => {
21 if (parentSchema.format !== 'date-time') {
22 throw new Error('Format should be date-time when using coerce-date');
23 }
24 if (onOrOff !== true) {
25 return lodash_1.identity;
26 }
27 return (v, _dataPath, obj, key) => {
28 if (obj === undefined || key === undefined) {
29 throw new Error('Cannot coerce a date at root level');
30 }
31 obj[key] = new Date(v);
32 return true;
33 };
34 },
35 });
36 return ajv;
37}
38function createClassValidator(schema, className, field) {
39 const ajv = createValidator();
40 for (const [k, v] of Object.entries(schema.definitions)) {
41 ajv.addSchema(v, `#/definitions/${k}`);
42 }
43 return lodash_1.fromPairs(Object.entries(schema.definitions[className].properties).map(([method, s]) => [
44 method, ajv.compile(s.properties[field]),
45 ]));
46}
47exports.createClassValidator = createClassValidator;
48function createReturnTypeValidator(schema, className) {
49 const ajv = createValidator();
50 for (const [k, v] of Object.entries(schema.definitions)) {
51 ajv.addSchema(v, `#/definitions/${k}`);
52 }
53 return lodash_1.fromPairs(Object.entries(schema.definitions[className].properties).map(([method, s]) => [
54 method, ajv.compile({ properties: lodash_1.pick(s.properties, 'returns') }),
55 ]));
56}
57exports.createReturnTypeValidator = createReturnTypeValidator;
58function createInterfaceValidator(schema, ifaceName) {
59 const ajv = createValidator();
60 for (const [k, v] of Object.entries(schema.definitions)) {
61 ajv.addSchema(v, `#/definitions/${k}`);
62 }
63 return ajv.compile(schema.definitions[ifaceName]);
64}
65exports.createInterfaceValidator = createInterfaceValidator;
66//# sourceMappingURL=common.js.map
\No newline at end of file