@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/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 nest-openapi
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="./docs/public/nest-openapi-logo.png" alt="nest-openapi-logo" height="84" />
|
|
3
|
+
</p>
|
|
4
|
+
|
|
5
|
+
<h1 align="center">@nest-openapi</h1>
|
|
6
|
+
|
|
7
|
+
<p align="center"><strong>OpenAPI-first validation for NestJS</strong></p>
|
|
8
|
+
|
|
9
|
+
<p align="center">
|
|
10
|
+
Single source of truth · Drop-in for existing controllers · Fast by design
|
|
11
|
+
</p>
|
|
12
|
+
|
|
13
|
+
[](https://www.npmjs.com/package/%40nest-openapi%2Fvalidator)
|
|
14
|
+

|
|
15
|
+

|
|
16
|
+
|
|
17
|
+
## Overview
|
|
18
|
+
|
|
19
|
+
`@nest-openapi` is a light-weight, focused toolkit for OpenAPI-driven NestJS apps.
|
|
20
|
+
Today it ships the **request/response validator** that derives schemas from your OpenAPI spec—so you don’t duplicate DTOs or hand-roll validation rules.
|
|
21
|
+
|
|
22
|
+
- **Single Source of Truth** — The OpenAPI spec is the contract; validation is generated from it.
|
|
23
|
+
- **Drop-in for NestJS** — Add a module; existing controllers keep working.
|
|
24
|
+
- **Fast by Design** — AJV under the hood, with caching and optional pre-compilation.
|
|
25
|
+
- **Express & Fastify** — Platform-agnostic validation.
|
|
26
|
+
- **Fine-Grained Control** — Per-route opt-out and overrides.
|
|
27
|
+
|
|
28
|
+
## Package
|
|
29
|
+
|
|
30
|
+
- **`@nest-openapi/validator`** — Automatic request/response validation using your OpenAPI 3.x spec.
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
npm i @nest-openapi/validator
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## Quick Start
|
|
41
|
+
|
|
42
|
+
### Basic Usage
|
|
43
|
+
|
|
44
|
+
```typescript
|
|
45
|
+
// app.module.ts
|
|
46
|
+
import { OpenApiValidatorModule } from "@nest-openapi/validator";
|
|
47
|
+
import * as openApiSpec from "./openapi.json";
|
|
48
|
+
|
|
49
|
+
@Module({
|
|
50
|
+
imports: [
|
|
51
|
+
OpenApiValidatorModule.forRoot({
|
|
52
|
+
specSource: { type: "object", spec: openApiSpec },
|
|
53
|
+
}),
|
|
54
|
+
],
|
|
55
|
+
})
|
|
56
|
+
export class AppModule {}
|
|
57
|
+
|
|
58
|
+
// That's it! All routes automatically validated
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### Advanced / Async Configuration
|
|
62
|
+
|
|
63
|
+
```typescript
|
|
64
|
+
// app.module.ts
|
|
65
|
+
@Module({
|
|
66
|
+
imports: [
|
|
67
|
+
OpenApiValidatorModule.forRootAsync({
|
|
68
|
+
imports: [ConfigModule],
|
|
69
|
+
useFactory: (config: ConfigService) => ({
|
|
70
|
+
specSource: { type: "object", spec: config.getOpenApiSpec() },
|
|
71
|
+
options: {
|
|
72
|
+
ajv: {
|
|
73
|
+
options: { strict: false },
|
|
74
|
+
configure: (ajv) => {
|
|
75
|
+
addFormats(ajv); // import addFormats from 'ajv-formats';
|
|
76
|
+
},
|
|
77
|
+
},
|
|
78
|
+
requestValidation: {
|
|
79
|
+
enable: false,
|
|
80
|
+
},
|
|
81
|
+
responseValidation: {
|
|
82
|
+
enable: true,
|
|
83
|
+
onValidationFailed: (context, errors) => {
|
|
84
|
+
console.log(errors);
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
}),
|
|
89
|
+
inject: [ConfigService],
|
|
90
|
+
}),
|
|
91
|
+
],
|
|
92
|
+
})
|
|
93
|
+
export class AppModule {}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Configuration Options
|
|
97
|
+
|
|
98
|
+
| Option | Type | Default | Description |
|
|
99
|
+
| ------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
|
|
100
|
+
| [`specSource`](#specsource) | `{ type: "object"; spec: OpenAPISpec } \| { type: "url"; spec: string } \| { type: "file"; spec: string }` | — | Provide your OpenAPI 3.x spec as an object, or point to it via URL or file path. |
|
|
101
|
+
| [`requestValidation`](#requestvalidation) | `RequestValidationOptions` | see [below](#requestvalidation) | Controls validation of incoming requests. |
|
|
102
|
+
| [`responseValidation`](#responsevalidation) | `ResponseValidationOptions` | see [below](#responsevalidation) | Controls validation of outgoing responses. |
|
|
103
|
+
| [`ajv`](#ajv) | `Ajv \| { options?: AjvOptions; configure?: (ajv: Ajv) => void }` | see [below](#ajv) | Override the default ajv instance or configure it |
|
|
104
|
+
| `precompileSchemas` | `boolean` | `false` | Precompile all route schemas during application bootstrap. This removes the first-request latency at the cost of longer start-up time. |
|
|
105
|
+
| `debug` | `boolean` | `false` | Verbose logs for troubleshooting. |
|
|
106
|
+
|
|
107
|
+
### `specSource`
|
|
108
|
+
|
|
109
|
+
| Type | Type | Typical use |
|
|
110
|
+
| ---------- | ------------- | ------------------------------------------------ |
|
|
111
|
+
| `"object"` | `OpenAPISpec` | Static spec object. |
|
|
112
|
+
| `"url"` | `string` | Link to a centralized or externally hosted spec. |
|
|
113
|
+
| `"file"` | `string` | Local file path to a json file. |
|
|
114
|
+
|
|
115
|
+
### `requestValidation`
|
|
116
|
+
|
|
117
|
+
| Option | Type | Default | Description |
|
|
118
|
+
| -------------------- | --------------------------------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------- |
|
|
119
|
+
| `enable` | `boolean` | `true` | Enable request validation globally. |
|
|
120
|
+
| `transform` | `boolean` | `false` | Coerce/transform inputs where schema allows (e.g., `"42"` → `42`). |
|
|
121
|
+
| `onValidationFailed` | `(ctx: ExecutionContext, errors: ValidationError[]) => void \| never` | throws `BadRequestException` with validation errors | Custom handler. Transform, throw your own exception, or log/ignore. |
|
|
122
|
+
|
|
123
|
+
### `responseValidation`
|
|
124
|
+
|
|
125
|
+
| Option | Type | Default | Description |
|
|
126
|
+
| -------------------- | --------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
|
|
127
|
+
| `enable` | `boolean` | `false` | Enable response validation globally. |
|
|
128
|
+
| `skipErrorResponses` | `boolean` | `true` | Skip validation for error responses (4xx/5xx status codes). Cant validate thrown errors, see [here](#error-response-validation). |
|
|
129
|
+
| `onValidationFailed` | `(ctx: ExecutionContext, errors: ValidationError[]) => void \| never` | warns and throws `InternalServer ErrorException` without validation errors | Custom handler. Transform, throw your own exception, or log/ignore. |
|
|
130
|
+
|
|
131
|
+
### `ajv`
|
|
132
|
+
|
|
133
|
+
| Option | Type | Default | Description |
|
|
134
|
+
| ----------- | -------------------- | ------------- | ----------------------------------------------------------------------- |
|
|
135
|
+
| (itself) | `Ajv` | a v8 instance | Supply a fully configured AJV instance. |
|
|
136
|
+
| `options` | `AjvOptions` | — | Initialize the internal AJV with these options (e.g., `strict: false`). |
|
|
137
|
+
| `configure` | `(ajv: Ajv) => void` | — | Hook to extend the instance (e.g., `addFormats(ajv)`). |
|
|
138
|
+
|
|
139
|
+
## Decorators
|
|
140
|
+
|
|
141
|
+
### Per-route control (skip/override)
|
|
142
|
+
|
|
143
|
+
```typescript
|
|
144
|
+
import { Validate } from "@nest-openapi/validator";
|
|
145
|
+
|
|
146
|
+
@Controller("users")
|
|
147
|
+
export class UsersController {
|
|
148
|
+
@Post()
|
|
149
|
+
@Validate({ request: false }) // Skip request validation for this route
|
|
150
|
+
createUser(@Body() userData: any) {
|
|
151
|
+
return this.usersService.create(userData);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
@Get(":id")
|
|
155
|
+
@Validate({ request: { param: false }, response: false }) // Skip param and response validation for this route
|
|
156
|
+
getUser(@Param("id") id: string) {
|
|
157
|
+
return this.usersService.findById(id);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
## Manual Validation
|
|
163
|
+
|
|
164
|
+
Inject the `OpenApiValidatorService` using the `OPENAPI_VALIDATOR` token for custom validation logic in guards, filters, services, or middleware:
|
|
165
|
+
|
|
166
|
+
```typescript
|
|
167
|
+
import { Injectable, Inject } from "@nestjs/common";
|
|
168
|
+
import { HttpArgumentsHost } from "@nestjs/common/interfaces";
|
|
169
|
+
import {
|
|
170
|
+
OPENAPI_VALIDATOR,
|
|
171
|
+
OpenApiValidatorService,
|
|
172
|
+
} from "@nest-openapi/validator";
|
|
173
|
+
|
|
174
|
+
@Injectable()
|
|
175
|
+
export class MyService {
|
|
176
|
+
constructor(
|
|
177
|
+
@Inject(OPENAPI_VALIDATOR)
|
|
178
|
+
private readonly validator: OpenApiValidatorService
|
|
179
|
+
) {}
|
|
180
|
+
|
|
181
|
+
validateData(httpContext: HttpArgumentsHost, responseBody) {
|
|
182
|
+
// Validate requests manually
|
|
183
|
+
const bodyOnlyErrors = this.validator.validateRequest(httpContext, {
|
|
184
|
+
body: true,
|
|
185
|
+
params: false,
|
|
186
|
+
query: false,
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
// Validate responses manually
|
|
190
|
+
const responseErrors = this.validator.validateResponse(
|
|
191
|
+
httpContext,
|
|
192
|
+
statusCode,
|
|
193
|
+
responseBody
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
### Error Response Validation
|
|
200
|
+
|
|
201
|
+
By default, the response validation interceptor only validates successful responses that flow through the normal pipeline. However, error responses (like `NotFoundException`, `BadRequestException`, etc.) bypass interceptors and go through exception filters.
|
|
202
|
+
|
|
203
|
+
To validate error responses, inject the validator service in your exception filter:
|
|
204
|
+
|
|
205
|
+
```typescript
|
|
206
|
+
import {
|
|
207
|
+
Catch,
|
|
208
|
+
ExceptionFilter,
|
|
209
|
+
ArgumentsHost,
|
|
210
|
+
Injectable,
|
|
211
|
+
Inject,
|
|
212
|
+
} from "@nestjs/common";
|
|
213
|
+
import {
|
|
214
|
+
OPENAPI_VALIDATOR,
|
|
215
|
+
OpenApiValidatorService,
|
|
216
|
+
} from "@nest-openapi/validator";
|
|
217
|
+
|
|
218
|
+
@Catch()
|
|
219
|
+
@Injectable()
|
|
220
|
+
export class GlobalExceptionFilter implements ExceptionFilter {
|
|
221
|
+
constructor(
|
|
222
|
+
@Inject(OPENAPI_VALIDATOR)
|
|
223
|
+
private readonly validator: OpenApiValidatorService
|
|
224
|
+
) {}
|
|
225
|
+
|
|
226
|
+
catch(exception: any, host: ArgumentsHost) {
|
|
227
|
+
const ctx = host.switchToHttp();
|
|
228
|
+
const response = ctx.getResponse();
|
|
229
|
+
|
|
230
|
+
const status = exception.getStatus?.() || 500;
|
|
231
|
+
const responseBody = {
|
|
232
|
+
message: exception.message,
|
|
233
|
+
statusCode: status,
|
|
234
|
+
timestamp: new Date().toISOString(),
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
const validationErrors = this.validator.validateResponse(
|
|
238
|
+
ctx,
|
|
239
|
+
status,
|
|
240
|
+
responseBody
|
|
241
|
+
);
|
|
242
|
+
|
|
243
|
+
if (validationErrors.length > 0) {
|
|
244
|
+
console.warn("Error response validation failed:", validationErrors);
|
|
245
|
+
// Handle validation errors as needed
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
response.status(status).json(responseBody);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
Then register your exception filter:
|
|
254
|
+
|
|
255
|
+
```typescript
|
|
256
|
+
// app.module.ts
|
|
257
|
+
@Module({
|
|
258
|
+
providers: [
|
|
259
|
+
{
|
|
260
|
+
provide: APP_FILTER,
|
|
261
|
+
useClass: GlobalExceptionFilter,
|
|
262
|
+
},
|
|
263
|
+
],
|
|
264
|
+
})
|
|
265
|
+
export class AppModule {}
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
## Error Handling
|
|
269
|
+
|
|
270
|
+
### Handle Validation Errors
|
|
271
|
+
|
|
272
|
+
By default, the library throws:
|
|
273
|
+
|
|
274
|
+
- `BadRequestException` for request validation failures, with detailed validation errors.
|
|
275
|
+
- `InternalServerErrorException` for response validation failures (without detailed errors, unless you provide a custom handler).
|
|
276
|
+
|
|
277
|
+
Validation errors follow the AJV `ErrorObject` format, extended with a `validationType` property:
|
|
278
|
+
|
|
279
|
+
```json
|
|
280
|
+
{
|
|
281
|
+
"message": "Validation failed",
|
|
282
|
+
"errors": [
|
|
283
|
+
{
|
|
284
|
+
"validationType": "body",
|
|
285
|
+
"instancePath": "/title",
|
|
286
|
+
"schemaPath": "#/properties/title/type",
|
|
287
|
+
"keyword": "type",
|
|
288
|
+
"params": { "type": "string" },
|
|
289
|
+
"message": "must be string"
|
|
290
|
+
}
|
|
291
|
+
]
|
|
292
|
+
}
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
You can override this behavior using the onValidationFailed handler option in [requestValidation](#requestvalidation) or [responseValidation](#responsevalidation).
|
|
296
|
+
|
|
297
|
+
Inside your handler, you can whether:
|
|
298
|
+
|
|
299
|
+
- Transform the error list and throw a custom exception.
|
|
300
|
+
- Log and ignore errors (return without throwing).
|
|
301
|
+
|
|
302
|
+
```typescript
|
|
303
|
+
OpenApiValidatorModule.forRoot({
|
|
304
|
+
specSource: { type: "object", spec: openApiSpec },
|
|
305
|
+
requestValidation: {
|
|
306
|
+
enable: true,
|
|
307
|
+
onValidationFailed: (context, errors) => {
|
|
308
|
+
// Custom error handling
|
|
309
|
+
throw new BadRequestException({
|
|
310
|
+
status: "validation_failed",
|
|
311
|
+
issues: errors.map((e) => ({
|
|
312
|
+
path: e.instancePath,
|
|
313
|
+
message: e.message,
|
|
314
|
+
received: e.data,
|
|
315
|
+
})),
|
|
316
|
+
});
|
|
317
|
+
},
|
|
318
|
+
},
|
|
319
|
+
});
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
## Performance and Compatibility
|
|
323
|
+
|
|
324
|
+
- Optional schema [pre-compilation](#configuration-options) removes first-hit latency at the cost of longer startup.
|
|
325
|
+
- Express and Fastify adopters are supported.
|
|
326
|
+
- Supports NestJS version >= 9
|