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