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