1 | "use strict";
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | Object.defineProperty(exports, "__esModule", { value: true });
|
7 | exports.validateValueAgainstSchema = exports.validateRequestBody = void 0;
|
8 | const tslib_1 = require("tslib");
|
9 | const openapi_v3_1 = require("@loopback/openapi-v3");
|
10 | const node_util_1 = tslib_1.__importDefault(require("node:util"));
|
11 | const debug_1 = tslib_1.__importDefault(require("debug"));
|
12 | const __1 = require("..");
|
13 | const ajv_factory_provider_1 = require("./ajv-factory.provider");
|
14 | const { openapiSchemaToJsonSchema: toJsonSchema, } = require('@openapi-contrib/openapi-schema-to-json-schema');
|
15 | const debug = (0, debug_1.default)('loopback:rest:validation');
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 | async function validateRequestBody(body, requestBodySpec, globalSchemas = {}, options = ajv_factory_provider_1.DEFAULT_AJV_VALIDATION_OPTIONS) {
|
27 | const required = requestBodySpec === null || requestBodySpec === void 0 ? void 0 : requestBodySpec.required;
|
28 | if (required && body.value == null) {
|
29 | throw Object.assign(new __1.HttpErrors.BadRequest('Request body is required'), {
|
30 | code: 'MISSING_REQUIRED_PARAMETER',
|
31 | parameterName: 'request body',
|
32 | });
|
33 | }
|
34 | if (!required && !body.value)
|
35 | return;
|
36 | const schema = body.schema;
|
37 |
|
38 | if (debug.enabled) {
|
39 | debug('Request body schema:', node_util_1.default.inspect(schema, { depth: null }));
|
40 | if (schema &&
|
41 | (0, openapi_v3_1.isReferenceObject)(schema) &&
|
42 | schema.$ref.startsWith('#/components/schemas/')) {
|
43 | const ref = schema.$ref.slice('#/components/schemas/'.length);
|
44 | debug(' referencing:', node_util_1.default.inspect(globalSchemas[ref], { depth: null }));
|
45 | }
|
46 | }
|
47 | if (!schema)
|
48 | return;
|
49 | options = { coerceTypes: !!body.coercionRequired, ...options };
|
50 | await validateValueAgainstSchema(body.value, schema, globalSchemas, {
|
51 | ...options,
|
52 | source: 'body',
|
53 | });
|
54 | }
|
55 | exports.validateRequestBody = validateRequestBody;
|
56 |
|
57 |
|
58 |
|
59 |
|
60 | function convertToJsonSchema(openapiSchema) {
|
61 | const jsonSchema = toJsonSchema(openapiSchema);
|
62 | delete jsonSchema['$schema'];
|
63 |
|
64 | if (debug.enabled) {
|
65 | debug('Converted OpenAPI schema to JSON schema: %s', node_util_1.default.inspect(jsonSchema, { depth: null }));
|
66 | }
|
67 | return jsonSchema;
|
68 | }
|
69 |
|
70 |
|
71 |
|
72 | const DEFAULT_COMPILED_SCHEMA_CACHE = new WeakMap();
|
73 |
|
74 |
|
75 |
|
76 |
|
77 | function getKeyForOptions(options = ajv_factory_provider_1.DEFAULT_AJV_VALIDATION_OPTIONS) {
|
78 | const ajvOptions = {};
|
79 |
|
80 | const keys = Object.keys(options).sort();
|
81 | for (const k of keys) {
|
82 | if (k === 'compiledSchemaCache')
|
83 | continue;
|
84 | ajvOptions[k] = options[k];
|
85 | }
|
86 | return JSON.stringify(ajvOptions);
|
87 | }
|
88 |
|
89 |
|
90 |
|
91 |
|
92 |
|
93 |
|
94 |
|
95 | async function validateValueAgainstSchema(
|
96 | // eslint-disable-next-line @typescript-eslint/no-explicit-any
|
97 | value, schema, globalSchemas = {}, options = {}) {
|
98 | var _a, _b, _c;
|
99 | let validate;
|
100 | const cache = (_a = options.compiledSchemaCache) !== null && _a !== void 0 ? _a : DEFAULT_COMPILED_SCHEMA_CACHE;
|
101 | const key = getKeyForOptions(options);
|
102 | let validatorMap;
|
103 | if (cache.has(schema)) {
|
104 | validatorMap = cache.get(schema);
|
105 | validate = validatorMap.get(key);
|
106 | }
|
107 | if (!validate) {
|
108 | const ajvFactory = (_b = options.ajvFactory) !== null && _b !== void 0 ? _b : new ajv_factory_provider_1.AjvFactoryProvider(options).value();
|
109 | const ajvInst = ajvFactory(options);
|
110 | validate = createValidator(schema, globalSchemas, ajvInst);
|
111 | validatorMap = validatorMap !== null && validatorMap !== void 0 ? validatorMap : new Map();
|
112 | validatorMap.set(key, validate);
|
113 | cache.set(schema, validatorMap);
|
114 | }
|
115 | let validationErrors = [];
|
116 | try {
|
117 | const validationResult = validate(value);
|
118 | debug(`Value from ${options.source} passed AJV validation.`, validationResult);
|
119 | return await validationResult;
|
120 | }
|
121 | catch (error) {
|
122 | validationErrors = error.errors;
|
123 | }
|
124 |
|
125 | if (debug.enabled) {
|
126 | debug('Invalid value: %s. Errors: %s', node_util_1.default.inspect(value, { depth: null }), node_util_1.default.inspect(validationErrors));
|
127 | }
|
128 | if (typeof options.ajvErrorTransformer === 'function') {
|
129 | validationErrors = options.ajvErrorTransformer(validationErrors);
|
130 | }
|
131 |
|
132 | if (options.source === 'body') {
|
133 | throw __1.RestHttpErrors.invalidRequestBody(buildErrorDetails(validationErrors));
|
134 | }
|
135 |
|
136 | throw __1.RestHttpErrors.invalidData(value, (_c = options.name) !== null && _c !== void 0 ? _c : '(unknown)', {
|
137 | details: buildErrorDetails(validationErrors),
|
138 | });
|
139 | }
|
140 | exports.validateValueAgainstSchema = validateValueAgainstSchema;
|
141 | function buildErrorDetails(validationErrors) {
|
142 | return validationErrors.map((e) => {
|
143 | var _a;
|
144 | return {
|
145 | path: e.instancePath,
|
146 | code: e.keyword,
|
147 | message: (_a = e.message) !== null && _a !== void 0 ? _a : `must pass validation rule ${e.keyword}`,
|
148 | info: e.params,
|
149 | };
|
150 | });
|
151 | }
|
152 |
|
153 |
|
154 |
|
155 |
|
156 |
|
157 |
|
158 | function createValidator(schema, globalSchemas = {}, ajvInst) {
|
159 | const jsonSchema = convertToJsonSchema(schema);
|
160 |
|
161 | const schemas = {};
|
162 | for (const name in globalSchemas) {
|
163 |
|
164 | schemas[name] = { ...globalSchemas[name], $async: true };
|
165 | }
|
166 | const schemaWithRef = { components: { schemas }, ...jsonSchema };
|
167 |
|
168 | schemaWithRef.$async = true;
|
169 | return ajvInst.compile(schemaWithRef);
|
170 | }
|
171 |
|
\ | No newline at end of file |