1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.AjvSchema = void 0;
|
4 | const fs = require("node:fs");
|
5 | const js_lib_1 = require("@naturalcycles/js-lib");
|
6 | const index_1 = require("../../index");
|
7 | const ajvValidationError_1 = require("./ajvValidationError");
|
8 | const getAjv_1 = require("./getAjv");
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | class AjvSchema {
|
16 | constructor(schema, cfg = {}) {
|
17 | this.schema = schema;
|
18 | this.cfg = {
|
19 | logErrors: true,
|
20 | logger: console,
|
21 | separator: '\n',
|
22 | ...cfg,
|
23 | ajv: cfg.ajv ||
|
24 | (0, getAjv_1.getAjv)({
|
25 | schemas: cfg.schemas?.map(s => {
|
26 | if (s instanceof AjvSchema)
|
27 | return s.schema;
|
28 | if (s instanceof js_lib_1.JsonSchemaAnyBuilder)
|
29 | return s.build();
|
30 | return s;
|
31 | }),
|
32 | coerceTypes: cfg.coerceTypes || false,
|
33 |
|
34 | }),
|
35 |
|
36 | objectName: cfg.objectName || (schema.$id ? (0, js_lib_1._substringBefore)(schema.$id, '.') : undefined),
|
37 | };
|
38 | this.validateFunction = this.cfg.ajv.compile(schema);
|
39 | }
|
40 | |
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 | static create(schema, cfg = {}) {
|
50 | if (schema instanceof AjvSchema)
|
51 | return schema;
|
52 | if (schema instanceof js_lib_1.JsonSchemaAnyBuilder) {
|
53 | return new AjvSchema(schema.build(), cfg);
|
54 | }
|
55 | return new AjvSchema(schema, cfg);
|
56 | }
|
57 | |
58 |
|
59 |
|
60 |
|
61 | static readJsonSync(filePath, cfg = {}) {
|
62 | (0, index_1.requireFileToExist)(filePath);
|
63 | const schema = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
64 | return new AjvSchema(schema, cfg);
|
65 | }
|
66 | |
67 |
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 | validate(obj, opt = {}) {
|
75 | const err = this.getValidationError(obj, opt);
|
76 | if (err)
|
77 | throw err;
|
78 | return obj;
|
79 | }
|
80 | getValidationError(obj, opt = {}) {
|
81 | if (this.isValid(obj))
|
82 | return;
|
83 | const errors = this.validateFunction.errors;
|
84 | const { objectId = (0, js_lib_1._isObject)(obj) ? obj['id'] : undefined, objectName = this.cfg.objectName, logErrors = this.cfg.logErrors, separator = this.cfg.separator, } = opt;
|
85 | const name = [objectName || 'Object', objectId].filter(Boolean).join('.');
|
86 | let message = this.cfg.ajv.errorsText(errors, {
|
87 | dataVar: name,
|
88 | separator,
|
89 | });
|
90 | const strValue = (0, index_1.inspectAny)(obj, { maxLen: 1000 });
|
91 | message = [message, 'Input: ' + strValue].join(separator);
|
92 | if (logErrors) {
|
93 | this.cfg.logger.error(errors);
|
94 | }
|
95 | return new ajvValidationError_1.AjvValidationError(message, (0, js_lib_1._filterNullishValues)({
|
96 | errors,
|
97 | userFriendly: true,
|
98 | objectName,
|
99 | objectId,
|
100 | }));
|
101 | }
|
102 | isValid(obj) {
|
103 | return this.validateFunction(obj);
|
104 | }
|
105 | }
|
106 | exports.AjvSchema = AjvSchema;
|