@nest-openapi/validator 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +326 -0
- package/dist/index.cjs +636 -0
- package/dist/index.d.cts +178 -0
- package/dist/index.d.ts +178 -0
- package/dist/index.js +609 -0
- package/package.json +103 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,636 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
var __decorateClass = (decorators, target, key, kind) => {
|
|
30
|
+
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
31
|
+
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
32
|
+
if (decorator = decorators[i])
|
|
33
|
+
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
34
|
+
if (kind && result) __defProp(target, key, result);
|
|
35
|
+
return result;
|
|
36
|
+
};
|
|
37
|
+
var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
|
|
38
|
+
|
|
39
|
+
// src/index.ts
|
|
40
|
+
var index_exports = {};
|
|
41
|
+
__export(index_exports, {
|
|
42
|
+
OPENAPI_VALIDATOR: () => OPENAPI_VALIDATOR,
|
|
43
|
+
OpenApiValidatorModule: () => OpenApiValidatorModule,
|
|
44
|
+
OpenApiValidatorService: () => OpenApiValidatorService,
|
|
45
|
+
Validate: () => Validate
|
|
46
|
+
});
|
|
47
|
+
module.exports = __toCommonJS(index_exports);
|
|
48
|
+
|
|
49
|
+
// src/modules/openapi-validator.module.ts
|
|
50
|
+
var import_common5 = require("@nestjs/common");
|
|
51
|
+
var import_core3 = require("@nestjs/core");
|
|
52
|
+
|
|
53
|
+
// src/services/openapi-validator.service.ts
|
|
54
|
+
var import_common = require("@nestjs/common");
|
|
55
|
+
var import_runtime = require("@nest-openapi/runtime");
|
|
56
|
+
var import_ajv = __toESM(require("ajv"), 1);
|
|
57
|
+
var OPENAPI_VALIDATOR_OPTIONS = "OPENAPI_VALIDATOR_OPTIONS";
|
|
58
|
+
var OPENAPI_VALIDATOR = "OPENAPI_VALIDATOR";
|
|
59
|
+
var OpenApiValidatorService = class {
|
|
60
|
+
constructor(runtime, options) {
|
|
61
|
+
this.runtime = runtime;
|
|
62
|
+
this.options = options;
|
|
63
|
+
this.debugLog = import_runtime.DebugUtil.createDebugFn(this.logger, this.options.debug || false);
|
|
64
|
+
if (this.options.ajv instanceof import_ajv.default) {
|
|
65
|
+
this.ajv = this.options.ajv;
|
|
66
|
+
} else {
|
|
67
|
+
this.ajv = new import_ajv.default({
|
|
68
|
+
allErrors: true,
|
|
69
|
+
strict: "log",
|
|
70
|
+
...this.options.requestValidation?.transform ? { coerceTypes: true, useDefaults: true } : {},
|
|
71
|
+
...this.options.ajv?.options
|
|
72
|
+
});
|
|
73
|
+
this.options.ajv?.configure?.(this.ajv);
|
|
74
|
+
}
|
|
75
|
+
if (this.options.debug) {
|
|
76
|
+
const { code: _code, uriResolver: _uriResolver, ...opts } = this.ajv.opts;
|
|
77
|
+
this.debugLog(`AJV instance created with options:
|
|
78
|
+
${JSON.stringify(opts, null, 2)}`);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
logger = new import_common.Logger("OpenApiValidator");
|
|
82
|
+
ajv;
|
|
83
|
+
openApiSpec;
|
|
84
|
+
debugLog;
|
|
85
|
+
async onApplicationBootstrap() {
|
|
86
|
+
this.openApiSpec = this.runtime.spec;
|
|
87
|
+
this.registerComponentSchemas();
|
|
88
|
+
if (this.options.precompileSchemas) await this.precompileSchemas();
|
|
89
|
+
}
|
|
90
|
+
get isSpecLoaded() {
|
|
91
|
+
return !!this.openApiSpec;
|
|
92
|
+
}
|
|
93
|
+
get validationOptions() {
|
|
94
|
+
return this.options;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Register all component schemas with AJV so it can resolve $ref references
|
|
98
|
+
*/
|
|
99
|
+
registerComponentSchemas() {
|
|
100
|
+
if (!this.openApiSpec?.components) {
|
|
101
|
+
this.debugLog("No components found to register");
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
const components = this.openApiSpec.components;
|
|
105
|
+
if (components.schemas) {
|
|
106
|
+
for (const [schemaName, schema] of Object.entries(components.schemas)) {
|
|
107
|
+
try {
|
|
108
|
+
this.ajv.addSchema(schema, `#/components/schemas/${schemaName}`);
|
|
109
|
+
this.debugLog(`Registered component schema: ${schemaName}`);
|
|
110
|
+
} catch (error) {
|
|
111
|
+
this.logger.warn(`Failed to register component schema '${schemaName}':`, error);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
if (components.parameters) {
|
|
116
|
+
for (const [paramName, param] of Object.entries(components.parameters)) {
|
|
117
|
+
try {
|
|
118
|
+
this.ajv.addSchema(param, `#/components/parameters/${paramName}`);
|
|
119
|
+
this.debugLog(`Registered component parameter: ${paramName}`);
|
|
120
|
+
} catch (error) {
|
|
121
|
+
this.logger.warn(`Failed to register component parameter '${paramName}':`, error);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (components.requestBodies) {
|
|
126
|
+
for (const [requestBodyName, requestBody] of Object.entries(components.requestBodies)) {
|
|
127
|
+
try {
|
|
128
|
+
this.ajv.addSchema(requestBody, `#/components/requestBodies/${requestBodyName}`);
|
|
129
|
+
this.debugLog(`Registered component request body: ${requestBodyName}`);
|
|
130
|
+
} catch (error) {
|
|
131
|
+
this.logger.warn(`Failed to register component request body '${requestBodyName}':`, error);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (components.responses) {
|
|
136
|
+
for (const [responseName, response] of Object.entries(components.responses)) {
|
|
137
|
+
try {
|
|
138
|
+
this.ajv.addSchema(response, `#/components/responses/${responseName}`);
|
|
139
|
+
this.debugLog(`Registered component response: ${responseName}`);
|
|
140
|
+
} catch (error) {
|
|
141
|
+
this.logger.warn(`Failed to register component response '${responseName}':`, error);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Walk the OpenAPI spec and eagerly compile all requestBody and parameter
|
|
148
|
+
* schemas. This is triggered when `options.performance.precompileSchemas === true` and
|
|
149
|
+
* eliminates runtime compilation overhead.
|
|
150
|
+
*/
|
|
151
|
+
async precompileSchemas() {
|
|
152
|
+
if (!this.openApiSpec || !this.openApiSpec.paths) return;
|
|
153
|
+
let schemasCompiled = 0;
|
|
154
|
+
const startTime = Date.now();
|
|
155
|
+
for (const [routePath, pathItem] of Object.entries(this.openApiSpec.paths)) {
|
|
156
|
+
for (const method of Object.keys(pathItem)) {
|
|
157
|
+
if (!["get", "post", "put", "patch", "delete", "options", "head", "trace"].includes(method.toLowerCase())) {
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
const operation = pathItem[method];
|
|
161
|
+
if (!operation) continue;
|
|
162
|
+
const operationName = `${method.toUpperCase()} ${routePath}`;
|
|
163
|
+
if (operation.requestBody) {
|
|
164
|
+
const bodySchema = this.runtime.schemaResolver.extractBodySchema(operation.requestBody);
|
|
165
|
+
if (bodySchema) {
|
|
166
|
+
try {
|
|
167
|
+
this.ajv.compile(bodySchema);
|
|
168
|
+
schemasCompiled++;
|
|
169
|
+
this.debugLog(`Precompiled schema "${operationName}" request body`);
|
|
170
|
+
} catch (error) {
|
|
171
|
+
this.logger.warn(`Failed to compile schema "${operationName}" request body`, error);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
if (operation.parameters) {
|
|
176
|
+
const parameterSchemas = this.runtime.schemaResolver.extractParameterSchemas(operation.parameters);
|
|
177
|
+
["path", "query"].forEach((loc) => {
|
|
178
|
+
for (const p of parameterSchemas[loc] || []) {
|
|
179
|
+
const sch = this.runtime.schemaResolver.resolveSchema(p.schema);
|
|
180
|
+
if (sch) {
|
|
181
|
+
try {
|
|
182
|
+
this.ajv.compile(this.getParameterSchema(sch));
|
|
183
|
+
schemasCompiled++;
|
|
184
|
+
this.debugLog(`Precompiled schema "${operationName}" request ${loc}`);
|
|
185
|
+
} catch (error) {
|
|
186
|
+
this.logger.warn(`Failed to compile schema "${operationName}" request ${loc}`, error);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
if (operation.responses) {
|
|
193
|
+
for (const [statusCode] of Object.entries(operation.responses)) {
|
|
194
|
+
const responseSchema = this.runtime.schemaResolver.extractResponseSchema(operation.responses, statusCode);
|
|
195
|
+
if (responseSchema) {
|
|
196
|
+
try {
|
|
197
|
+
this.ajv.compile(responseSchema);
|
|
198
|
+
schemasCompiled++;
|
|
199
|
+
this.debugLog(`Precompiled schema "${operationName}" response "${statusCode}"`);
|
|
200
|
+
} catch (error) {
|
|
201
|
+
this.logger.warn(`Failed to compile schema "${operationName}" response "${statusCode}"`, error);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
const duration = Date.now() - startTime;
|
|
209
|
+
this.debugLog(`Precompiled ${schemasCompiled} schemas in ${duration}ms`);
|
|
210
|
+
}
|
|
211
|
+
findOperation(method, path) {
|
|
212
|
+
if (!this.openApiSpec) return null;
|
|
213
|
+
const openApiPath = path.replace(/:([^/]+)/g, "{$1}");
|
|
214
|
+
const operation = this.openApiSpec.paths[openApiPath]?.[method.toLowerCase()];
|
|
215
|
+
if (!operation) this.debugLog(`Found no operation for ${method} ${path}`);
|
|
216
|
+
return operation;
|
|
217
|
+
}
|
|
218
|
+
validateWithSchema(schema, data, type) {
|
|
219
|
+
const validator = this.ajv.compile(schema);
|
|
220
|
+
if (!validator(data)) {
|
|
221
|
+
const errors = validator.errors?.map((error) => ({
|
|
222
|
+
validationType: type,
|
|
223
|
+
...error
|
|
224
|
+
}));
|
|
225
|
+
if (errors?.length) {
|
|
226
|
+
if (this.options.debug) this.debugLog(`Validation failed for "${type}"
|
|
227
|
+
|
|
228
|
+
Schema:
|
|
229
|
+
${JSON.stringify(schema, null, 2)}
|
|
230
|
+
|
|
231
|
+
Data:
|
|
232
|
+
${JSON.stringify(data, null, 2)}
|
|
233
|
+
|
|
234
|
+
Errors:
|
|
235
|
+
${JSON.stringify(errors, null, 2)}`);
|
|
236
|
+
return errors;
|
|
237
|
+
}
|
|
238
|
+
;
|
|
239
|
+
}
|
|
240
|
+
if (this.options.debug) this.debugLog(`Validation passed for "${type}"
|
|
241
|
+
|
|
242
|
+
Schema:
|
|
243
|
+
${JSON.stringify(schema, null, 2)}
|
|
244
|
+
|
|
245
|
+
Data:
|
|
246
|
+
${JSON.stringify(data, null, 2)}`);
|
|
247
|
+
return null;
|
|
248
|
+
}
|
|
249
|
+
validateRequest(httpContext, options = { body: true, params: true, query: true }) {
|
|
250
|
+
if (!this.isSpecLoaded) return [];
|
|
251
|
+
const validationOptions = options;
|
|
252
|
+
const requestData = import_runtime.PlatformUtil.extractRequestData(httpContext);
|
|
253
|
+
const { method, path, body } = requestData;
|
|
254
|
+
const { params, query } = requestData;
|
|
255
|
+
if (!method || !path) return [];
|
|
256
|
+
const operation = this.findOperation(method, path);
|
|
257
|
+
if (!operation) return [];
|
|
258
|
+
const errors = [];
|
|
259
|
+
if (operation.parameters) {
|
|
260
|
+
const parameterSchemas = this.runtime.schemaResolver.extractParameterSchemas(operation.parameters);
|
|
261
|
+
if (validationOptions.params && parameterSchemas.path.length > 0 && params) {
|
|
262
|
+
const pathErrors = this.validateParameters(parameterSchemas.path, params, "path");
|
|
263
|
+
if (pathErrors.length) errors.push(...pathErrors);
|
|
264
|
+
}
|
|
265
|
+
if (validationOptions.query && parameterSchemas.query.length > 0 && query) {
|
|
266
|
+
const queryErrors = this.validateParameters(parameterSchemas.query, query, "query");
|
|
267
|
+
if (queryErrors.length) errors.push(...queryErrors);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
if (validationOptions.body && operation.requestBody && body !== void 0) {
|
|
271
|
+
const bodySchema = this.runtime.schemaResolver.extractBodySchema(operation.requestBody);
|
|
272
|
+
if (bodySchema) {
|
|
273
|
+
const bodyErrors = this.validateWithSchema(bodySchema, body, "body");
|
|
274
|
+
if (bodyErrors) errors.push(...bodyErrors);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
if (this.options.requestValidation?.transform) {
|
|
278
|
+
import_runtime.PlatformUtil.setTransformedRequestData(httpContext, { body, params, query });
|
|
279
|
+
}
|
|
280
|
+
return errors;
|
|
281
|
+
}
|
|
282
|
+
validateParameters(parameters, data, type) {
|
|
283
|
+
const errors = [];
|
|
284
|
+
for (const param of parameters) {
|
|
285
|
+
const value = data[param.name];
|
|
286
|
+
const isRequired = param.required === true;
|
|
287
|
+
if (isRequired && (value === void 0 || value === null || value === "")) {
|
|
288
|
+
this.debugLog(`Found missing required ${type} parameter: ${param.name}`);
|
|
289
|
+
errors.push({
|
|
290
|
+
validationType: type,
|
|
291
|
+
keyword: "required",
|
|
292
|
+
instancePath: `/${param.name}`,
|
|
293
|
+
schemaPath: `#/properties/${param.name}/required`,
|
|
294
|
+
params: { missingProperty: param.name },
|
|
295
|
+
message: `${param.name} is required`
|
|
296
|
+
});
|
|
297
|
+
continue;
|
|
298
|
+
}
|
|
299
|
+
if (value !== void 0 && param.schema) {
|
|
300
|
+
const schema = this.runtime.schemaResolver.resolveSchema(param.schema);
|
|
301
|
+
if (schema) {
|
|
302
|
+
const paramValue = { value };
|
|
303
|
+
const paramErrors = this.validateWithSchema(this.getParameterSchema(schema), paramValue, type);
|
|
304
|
+
data[param.name] = paramValue.value;
|
|
305
|
+
if (paramErrors) errors.push(...paramErrors);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
return errors;
|
|
310
|
+
}
|
|
311
|
+
validateResponse(httpContext, statusCode, responseBody) {
|
|
312
|
+
if (!this.isSpecLoaded) return [];
|
|
313
|
+
const requestData = import_runtime.PlatformUtil.extractRequestData(httpContext);
|
|
314
|
+
const { method, path } = requestData;
|
|
315
|
+
if (!method || !path) return [];
|
|
316
|
+
const operation = this.findOperation(method, path);
|
|
317
|
+
if (!operation) return [];
|
|
318
|
+
if (!operation.responses) return [];
|
|
319
|
+
const responseSchema = this.runtime.schemaResolver.extractResponseSchema(operation.responses, statusCode);
|
|
320
|
+
if (responseSchema) {
|
|
321
|
+
const responseErrors = this.validateWithSchema(
|
|
322
|
+
responseSchema,
|
|
323
|
+
responseBody,
|
|
324
|
+
"response"
|
|
325
|
+
);
|
|
326
|
+
return responseErrors || [];
|
|
327
|
+
}
|
|
328
|
+
return [];
|
|
329
|
+
}
|
|
330
|
+
getParameterSchema(schema) {
|
|
331
|
+
return {
|
|
332
|
+
type: "object",
|
|
333
|
+
properties: {
|
|
334
|
+
value: schema
|
|
335
|
+
},
|
|
336
|
+
required: ["value"]
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
OpenApiValidatorService = __decorateClass([
|
|
341
|
+
(0, import_common.Injectable)(),
|
|
342
|
+
__decorateParam(0, (0, import_common.Inject)(import_runtime.OpenApiRuntimeService)),
|
|
343
|
+
__decorateParam(1, (0, import_common.Inject)(OPENAPI_VALIDATOR_OPTIONS))
|
|
344
|
+
], OpenApiValidatorService);
|
|
345
|
+
|
|
346
|
+
// src/interceptors/request-validation.interceptor.ts
|
|
347
|
+
var import_common3 = require("@nestjs/common");
|
|
348
|
+
var import_core = require("@nestjs/core");
|
|
349
|
+
var import_runtime3 = require("@nest-openapi/runtime");
|
|
350
|
+
|
|
351
|
+
// src/decorators/validate.decorator.ts
|
|
352
|
+
var import_common2 = require("@nestjs/common");
|
|
353
|
+
var VALIDATE_KEY = "VALIDATE";
|
|
354
|
+
var Validate = (options = {}) => (0, import_common2.SetMetadata)(VALIDATE_KEY, options);
|
|
355
|
+
|
|
356
|
+
// src/interceptors/request-validation.interceptor.ts
|
|
357
|
+
var RequestValidationInterceptor = class {
|
|
358
|
+
constructor(validatorService, reflector) {
|
|
359
|
+
this.validatorService = validatorService;
|
|
360
|
+
this.reflector = reflector;
|
|
361
|
+
this.debugLog = import_runtime3.DebugUtil.createDebugFn(this.logger, this.validatorService.validationOptions.debug || false);
|
|
362
|
+
}
|
|
363
|
+
logger = new import_common3.Logger("OpenApiValidator");
|
|
364
|
+
debugLog;
|
|
365
|
+
async intercept(context, next) {
|
|
366
|
+
if (!this.validatorService.openApiSpec) {
|
|
367
|
+
this.debugLog("Skipped request validation - OpenAPI spec not loaded");
|
|
368
|
+
return next.handle();
|
|
369
|
+
}
|
|
370
|
+
if (this.validatorService.validationOptions.requestValidation?.enable === false) {
|
|
371
|
+
this.debugLog("Skipped request validation due to configuration");
|
|
372
|
+
return next.handle();
|
|
373
|
+
}
|
|
374
|
+
const validationConfig = this.getValidationDecorator(context);
|
|
375
|
+
if (validationConfig === false) {
|
|
376
|
+
this.debugLog("Skipped request validation due to configuration");
|
|
377
|
+
return next.handle();
|
|
378
|
+
}
|
|
379
|
+
const httpContext = context.switchToHttp();
|
|
380
|
+
try {
|
|
381
|
+
const errors = this.validatorService.validateRequest(httpContext, validationConfig);
|
|
382
|
+
if (errors.length > 0) {
|
|
383
|
+
if (this.validatorService.validationOptions.requestValidation?.onValidationFailed) {
|
|
384
|
+
this.validatorService.validationOptions.requestValidation.onValidationFailed(context, errors);
|
|
385
|
+
} else {
|
|
386
|
+
this.defaultOnValidationFailed(errors);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
} catch (error) {
|
|
390
|
+
this.debugLog("Thrown error onValidationFailed", error);
|
|
391
|
+
throw error;
|
|
392
|
+
}
|
|
393
|
+
return next.handle();
|
|
394
|
+
}
|
|
395
|
+
getValidationDecorator(context) {
|
|
396
|
+
const validateMetadata = this.reflector.getAllAndOverride(
|
|
397
|
+
VALIDATE_KEY,
|
|
398
|
+
[context.getHandler(), context.getClass()]
|
|
399
|
+
);
|
|
400
|
+
if (validateMetadata) {
|
|
401
|
+
const { request } = validateMetadata;
|
|
402
|
+
if (request === false) return false;
|
|
403
|
+
if (request === true) {
|
|
404
|
+
return { params: true, query: true, body: true };
|
|
405
|
+
}
|
|
406
|
+
if (typeof request === "object" && request !== null) {
|
|
407
|
+
return {
|
|
408
|
+
params: request.params ?? true,
|
|
409
|
+
query: request.query ?? true,
|
|
410
|
+
body: request.body ?? true
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
return { params: true, query: true, body: true };
|
|
415
|
+
}
|
|
416
|
+
defaultOnValidationFailed(errors) {
|
|
417
|
+
throw new import_common3.BadRequestException({
|
|
418
|
+
message: "Validation failed",
|
|
419
|
+
errors
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
};
|
|
423
|
+
RequestValidationInterceptor = __decorateClass([
|
|
424
|
+
(0, import_common3.Injectable)(),
|
|
425
|
+
__decorateParam(0, (0, import_common3.Inject)(OPENAPI_VALIDATOR)),
|
|
426
|
+
__decorateParam(1, (0, import_common3.Inject)(import_core.Reflector))
|
|
427
|
+
], RequestValidationInterceptor);
|
|
428
|
+
|
|
429
|
+
// src/interceptors/response-validation.interceptor.ts
|
|
430
|
+
var import_common4 = require("@nestjs/common");
|
|
431
|
+
var import_operators = require("rxjs/operators");
|
|
432
|
+
var import_core2 = require("@nestjs/core");
|
|
433
|
+
var import_runtime5 = require("@nest-openapi/runtime");
|
|
434
|
+
var ResponseValidationInterceptor = class {
|
|
435
|
+
constructor(validatorService, reflector) {
|
|
436
|
+
this.validatorService = validatorService;
|
|
437
|
+
this.reflector = reflector;
|
|
438
|
+
this.debugLog = import_runtime5.DebugUtil.createDebugFn(this.logger, this.validatorService.validationOptions.debug || false);
|
|
439
|
+
}
|
|
440
|
+
logger = new import_common4.Logger("OpenApiValidator");
|
|
441
|
+
debugLog;
|
|
442
|
+
intercept(context, next) {
|
|
443
|
+
if (!this.validatorService.openApiSpec) {
|
|
444
|
+
this.debugLog("Skipped response validation - OpenAPI spec not loaded");
|
|
445
|
+
return next.handle();
|
|
446
|
+
}
|
|
447
|
+
const shouldValidateResponse = this.shouldValidateResponse(context);
|
|
448
|
+
if (!shouldValidateResponse) {
|
|
449
|
+
this.debugLog("Skipped response validation due to configuration");
|
|
450
|
+
return next.handle();
|
|
451
|
+
}
|
|
452
|
+
const httpContext = context.switchToHttp();
|
|
453
|
+
const response = context.switchToHttp().getResponse();
|
|
454
|
+
return next.handle().pipe(
|
|
455
|
+
(0, import_operators.map)((data) => {
|
|
456
|
+
try {
|
|
457
|
+
const shouldSkipErrorResponses = this.validatorService.validationOptions.responseValidation?.skipErrorResponses;
|
|
458
|
+
if (shouldSkipErrorResponses && response.statusCode >= 400) {
|
|
459
|
+
this.debugLog(`Skipped response validation for error status code "${response.statusCode}"`);
|
|
460
|
+
return data;
|
|
461
|
+
}
|
|
462
|
+
const errors = this.validatorService.validateResponse(httpContext, response.statusCode, data);
|
|
463
|
+
if (errors.length > 0) {
|
|
464
|
+
if (this.validatorService.validationOptions.responseValidation?.onValidationFailed) {
|
|
465
|
+
this.validatorService.validationOptions.responseValidation.onValidationFailed(context, errors);
|
|
466
|
+
} else {
|
|
467
|
+
this.defaultOnValidationFailed(data, errors);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
} catch (error) {
|
|
471
|
+
this.debugLog("Thrown error onValidationFailed", error);
|
|
472
|
+
throw error;
|
|
473
|
+
}
|
|
474
|
+
return data;
|
|
475
|
+
})
|
|
476
|
+
);
|
|
477
|
+
}
|
|
478
|
+
shouldValidateResponse(context) {
|
|
479
|
+
const validateMetadata = this.reflector.getAllAndOverride(
|
|
480
|
+
VALIDATE_KEY,
|
|
481
|
+
[context.getHandler(), context.getClass()]
|
|
482
|
+
);
|
|
483
|
+
if (validateMetadata) {
|
|
484
|
+
const { response } = validateMetadata;
|
|
485
|
+
if (response !== void 0) return response === true;
|
|
486
|
+
}
|
|
487
|
+
return this.validatorService.validationOptions.responseValidation?.enable === true;
|
|
488
|
+
}
|
|
489
|
+
defaultOnValidationFailed(data, errors) {
|
|
490
|
+
this.logger.warn(`Response validation failed:
|
|
491
|
+
Data: ${JSON.stringify(data)}
|
|
492
|
+
Errors: ${JSON.stringify(errors)}`);
|
|
493
|
+
throw new import_common4.InternalServerErrorException({ message: "Internal server error: Response validation failed" });
|
|
494
|
+
}
|
|
495
|
+
};
|
|
496
|
+
ResponseValidationInterceptor = __decorateClass([
|
|
497
|
+
(0, import_common4.Injectable)(),
|
|
498
|
+
__decorateParam(0, (0, import_common4.Inject)(OPENAPI_VALIDATOR)),
|
|
499
|
+
__decorateParam(1, (0, import_common4.Inject)(import_core2.Reflector))
|
|
500
|
+
], ResponseValidationInterceptor);
|
|
501
|
+
|
|
502
|
+
// src/modules/openapi-validator.module.ts
|
|
503
|
+
var import_runtime7 = require("@nest-openapi/runtime");
|
|
504
|
+
var OpenApiValidatorModule = class {
|
|
505
|
+
/**
|
|
506
|
+
* Configure the OpenAPI validator module with static options
|
|
507
|
+
*/
|
|
508
|
+
static forRoot(options) {
|
|
509
|
+
const defaultOptions = {
|
|
510
|
+
debug: false,
|
|
511
|
+
requestValidation: { enable: true },
|
|
512
|
+
responseValidation: { enable: false, skipErrorResponses: true }
|
|
513
|
+
};
|
|
514
|
+
const mergedOptions = { ...defaultOptions, ...options };
|
|
515
|
+
const providers = [
|
|
516
|
+
// Validator options
|
|
517
|
+
{ provide: OPENAPI_VALIDATOR_OPTIONS, useValue: mergedOptions },
|
|
518
|
+
// Bridge validator options -> runtime options
|
|
519
|
+
{
|
|
520
|
+
provide: import_runtime7.OPENAPI_RUNTIME_OPTIONS,
|
|
521
|
+
useValue: {
|
|
522
|
+
specSource: mergedOptions.specSource,
|
|
523
|
+
debug: mergedOptions.debug
|
|
524
|
+
}
|
|
525
|
+
},
|
|
526
|
+
// Core services
|
|
527
|
+
{
|
|
528
|
+
provide: import_runtime7.OpenApiRuntimeService,
|
|
529
|
+
useFactory: async (runtimeOptions) => {
|
|
530
|
+
const svc = new import_runtime7.OpenApiRuntimeService(runtimeOptions);
|
|
531
|
+
await svc.onModuleInit();
|
|
532
|
+
return svc;
|
|
533
|
+
},
|
|
534
|
+
inject: [import_runtime7.OPENAPI_RUNTIME_OPTIONS]
|
|
535
|
+
},
|
|
536
|
+
OpenApiValidatorService,
|
|
537
|
+
{ provide: OPENAPI_VALIDATOR, useExisting: OpenApiValidatorService },
|
|
538
|
+
// Interceptors
|
|
539
|
+
{ provide: import_core3.APP_INTERCEPTOR, useClass: RequestValidationInterceptor }
|
|
540
|
+
];
|
|
541
|
+
if (mergedOptions.responseValidation?.enable) {
|
|
542
|
+
providers.push({
|
|
543
|
+
provide: import_core3.APP_INTERCEPTOR,
|
|
544
|
+
useClass: ResponseValidationInterceptor
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
return {
|
|
548
|
+
module: OpenApiValidatorModule,
|
|
549
|
+
providers,
|
|
550
|
+
exports: [
|
|
551
|
+
OPENAPI_VALIDATOR_OPTIONS,
|
|
552
|
+
OPENAPI_VALIDATOR,
|
|
553
|
+
import_runtime7.OpenApiRuntimeService,
|
|
554
|
+
OpenApiValidatorService
|
|
555
|
+
]
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* Configure the OpenAPI validator module with async options
|
|
560
|
+
*/
|
|
561
|
+
static forRootAsync(options) {
|
|
562
|
+
const defaultOptions = {
|
|
563
|
+
debug: false,
|
|
564
|
+
requestValidation: { enable: true },
|
|
565
|
+
responseValidation: { enable: false, skipErrorResponses: true }
|
|
566
|
+
};
|
|
567
|
+
const providers = [
|
|
568
|
+
// Build validator options first
|
|
569
|
+
{
|
|
570
|
+
provide: OPENAPI_VALIDATOR_OPTIONS,
|
|
571
|
+
useFactory: async (...args) => {
|
|
572
|
+
const user = options.useFactory ? await options.useFactory(...args) : {};
|
|
573
|
+
return { ...defaultOptions, ...user };
|
|
574
|
+
},
|
|
575
|
+
inject: options.inject || []
|
|
576
|
+
},
|
|
577
|
+
// Map validator options -> runtime options (no user config for runtime)
|
|
578
|
+
{
|
|
579
|
+
provide: import_runtime7.OPENAPI_RUNTIME_OPTIONS,
|
|
580
|
+
useFactory: (validatorOpts) => ({
|
|
581
|
+
specSource: validatorOpts.specSource,
|
|
582
|
+
debug: validatorOpts.debug,
|
|
583
|
+
precompileSchemas: validatorOpts.precompileSchemas
|
|
584
|
+
}),
|
|
585
|
+
inject: [OPENAPI_VALIDATOR_OPTIONS]
|
|
586
|
+
},
|
|
587
|
+
// Core services
|
|
588
|
+
{
|
|
589
|
+
provide: import_runtime7.OpenApiRuntimeService,
|
|
590
|
+
useFactory: async (runtimeOptions) => {
|
|
591
|
+
const svc = new import_runtime7.OpenApiRuntimeService(runtimeOptions);
|
|
592
|
+
await svc.onModuleInit();
|
|
593
|
+
return svc;
|
|
594
|
+
},
|
|
595
|
+
inject: [import_runtime7.OPENAPI_RUNTIME_OPTIONS]
|
|
596
|
+
},
|
|
597
|
+
OpenApiValidatorService,
|
|
598
|
+
{ provide: OPENAPI_VALIDATOR, useExisting: OpenApiValidatorService },
|
|
599
|
+
// Interceptors
|
|
600
|
+
{ provide: import_core3.APP_INTERCEPTOR, useClass: RequestValidationInterceptor },
|
|
601
|
+
// Conditionally add response validation
|
|
602
|
+
{
|
|
603
|
+
provide: import_core3.APP_INTERCEPTOR,
|
|
604
|
+
useFactory: (validatorOptions, validatorService, reflector) => {
|
|
605
|
+
if (validatorOptions.responseValidation?.enable) {
|
|
606
|
+
return new ResponseValidationInterceptor(validatorService, reflector);
|
|
607
|
+
}
|
|
608
|
+
return { intercept: (_ctx, next) => next.handle() };
|
|
609
|
+
},
|
|
610
|
+
inject: [OPENAPI_VALIDATOR_OPTIONS, OpenApiValidatorService, import_core3.Reflector]
|
|
611
|
+
}
|
|
612
|
+
];
|
|
613
|
+
return {
|
|
614
|
+
module: OpenApiValidatorModule,
|
|
615
|
+
imports: options.imports || [],
|
|
616
|
+
providers,
|
|
617
|
+
exports: [
|
|
618
|
+
OPENAPI_VALIDATOR_OPTIONS,
|
|
619
|
+
OPENAPI_VALIDATOR,
|
|
620
|
+
import_runtime7.OpenApiRuntimeService,
|
|
621
|
+
OpenApiValidatorService
|
|
622
|
+
]
|
|
623
|
+
};
|
|
624
|
+
}
|
|
625
|
+
};
|
|
626
|
+
OpenApiValidatorModule = __decorateClass([
|
|
627
|
+
(0, import_common5.Global)(),
|
|
628
|
+
(0, import_common5.Module)({})
|
|
629
|
+
], OpenApiValidatorModule);
|
|
630
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
631
|
+
0 && (module.exports = {
|
|
632
|
+
OPENAPI_VALIDATOR,
|
|
633
|
+
OpenApiValidatorModule,
|
|
634
|
+
OpenApiValidatorService,
|
|
635
|
+
Validate
|
|
636
|
+
});
|