1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | const lodash_1 = require("lodash");
|
4 | const AjvCtor = require("ajv");
|
5 | class ValidationError extends Error {
|
6 | constructor(message, errors) {
|
7 | super(message);
|
8 | this.errors = errors;
|
9 | this.name = 'ValidationError';
|
10 | }
|
11 | }
|
12 | exports.ValidationError = ValidationError;
|
13 | function 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 | }
|
38 |
|
39 |
|
40 |
|
41 |
|
42 | function escapeJsonPointer(ptr) {
|
43 | return encodeURIComponent(ptr.replace(/~/g, '~0').replace(/\//g, '~1'));
|
44 | }
|
45 |
|
46 | function createClassValidator(schema, className, field) {
|
47 | const ajv = createValidator();
|
48 | for (const [k, v] of Object.entries(schema.definitions)) {
|
49 | ajv.addSchema(v, `#/definitions/${escapeJsonPointer(k)}`);
|
50 | }
|
51 | return lodash_1.fromPairs(Object.entries(schema.definitions[className].properties).map(([method, s]) => [
|
52 | method, ajv.compile(s.properties[field]),
|
53 | ]));
|
54 | }
|
55 | exports.createClassValidator = createClassValidator;
|
56 | function createReturnTypeValidator(schema, className) {
|
57 | const ajv = createValidator();
|
58 | for (const [k, v] of Object.entries(schema.definitions)) {
|
59 | ajv.addSchema(v, `#/definitions/${escapeJsonPointer(k)}`);
|
60 | }
|
61 | return lodash_1.fromPairs(Object.entries(schema.definitions[className].properties).map(([method, s]) => [
|
62 | method, ajv.compile({ properties: lodash_1.pick(s.properties, 'returns') }),
|
63 | ]));
|
64 | }
|
65 | exports.createReturnTypeValidator = createReturnTypeValidator;
|
66 |
|
\ | No newline at end of file |