Gathering detailed insights and metrics for nestjs-typebox
Gathering detailed insights and metrics for nestjs-typebox
Gathering detailed insights and metrics for nestjs-typebox
Gathering detailed insights and metrics for nestjs-typebox
Various utilities for integrating Typebox and NestJs for both validation and OpenApi schema generation
npm install nestjs-typebox
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
29 Stars
207 Commits
5 Forks
4 Watching
2 Branches
3 Contributors
Updated on 24 Nov 2024
TypeScript (97.95%)
JavaScript (2.05%)
Cumulative downloads
Total Downloads
Last day
87.1%
348
Compared to previous day
Last week
5.5%
1,524
Compared to previous week
Last month
3.1%
6,443
Compared to previous month
Last year
365.6%
33,827
Compared to previous year
5
19
This library provides helper utilities for writing and validating NestJS APIs using TypeBox as an alternative to class-validator/class-transformer. Can be configured to patch @nestjs/swagger allowing OpenAPI generation to continue working. Supports property defaults, basic type coercion, transforms, stripping unknown properties, and custom error messages. See typebox docs for more info.
1npm i nestjs-typebox @sinclair/typebox
Important: Note that
nestjs-typebox
is an alternative to the class-validator DTO approach detailed in the NestJS docs, and is meant to fully replace it and all of the built-in validation/parsing pipes. Make sure you remove any global validation/parsing pipes before installing this library and avoid using any local validation/parsing pipe decorators in combination with this library's decorators.
The example below demonstrates a discriminated union type, which cannot be achieved using class-based introspection approaches like that of class-validator.
1import { Type } from '@sinclair/typebox'; 2 3export const PetSchemaBase = Type.Object({ 4 id: Type.Number(), 5 name: Type.String({ 6 description: "The pet's name", 7 examples: ['Figaro'], 8 }), 9 microchip: Type.String(){ 10 minLength: 10, 11 description: 'Secret microchip number. Not sent to client', 12 errorMessage: '"microchip" is required and must be at least 10 characters.' 13 }, 14}); 15 16export const CatSchema = Type.Composite([ 17 PetSchemaBase, 18 Type.Object({ 19 type: Type.Literal('cat'), 20 breed: Type.Union([Type.Literal('shorthair'), Type.Literal('persian'), Type.Literal('siamese')]), 21 }), 22]); 23 24export const DogSchema = Type.Composite([ 25 PetSchemaBase, 26 Type.Object({ 27 type: Type.Literal('dog'), 28 breed: Type.Union([Type.Literal('shiba-inu'), Type.Literal('poodle'), Type.Literal('dachshund')]), 29 }), 30]); 31 32export const PetSchema = Type.Union([CatSchema, DogSchema]); 33export type Pet = Static<typeof PetSchema>;
The example below shows two different decorators and their usage, calling out default configuration. Schemas have all been defined inline for brevity, but could just as easily be defined elsewhere and reused. The primary benefit of using @HttpEndpoint over @Validator is the additional validation enforcing path parameters to be properly defined as request "param" validators. Otherwise, it simply passes through options specified in
validate
to the underlying @Validator decorator.
1import { Type } from '@sinclair/typebox'; 2import { Validate, HttpEndpoint } from 'nestjs-typebox'; 3 4@Controller('pets') 5export class PetController { 6 constructor(private readonly petService: PetService) {} 7 8 @Get() 9 @Validate({ 10 response: { schema: Type.Array(Type.Omit(PetSchema, ['microchip'])), stripUnknownProps: true }, 11 }) 12 async getPets() { 13 return this.petService.getPets(); 14 } 15 16 @Get(':id') 17 @Validate({ 18 // stripUnknownProps is true by default for response validators 19 // so this shorthand is equivalent 20 response: Type.Omit(PetSchema, ['microchip']), 21 request: [ 22 // coerceTypes is true by default for "param" and "query" request validators 23 { name: 'id', type: 'param', schema: Type.Number(), coerceTypes: true }, 24 ], 25 }) 26 // no need to use @Param() decorator here since the @Validate() decorator will 27 // automatically attach a pipe to populate and convert the paramater value 28 async getPet(id: number) { 29 return this.petService.getPet(id); 30 } 31 32 @Post() 33 @Validate({ 34 response: Type.Omit(PetSchema, ['microchip']), 35 request: [ 36 // if "name" not provided, method name will be used 37 { type: 'body', schema: Type.Omit(PetSchema, 'id') }, 38 ], 39 }) 40 async createPet(data: Omit<Pet, 'id'>) { 41 return this.petService.createPet(data); 42 } 43 44 @HttpEndpoint({ 45 method: 'PATCH', 46 path: ':id', 47 validate: { 48 response: Type.Omit(PetSchema, ['microchip']), 49 request: [ 50 { name: 'id', type: 'param', schema: Type.Number() }, 51 { type: 'body', schema: Type.Partial(Type.Omit(PetSchema, ['id'])) }, 52 ], 53 }, 54 }) 55 // the order of the controller method parameters must correspond to the order/types of 56 // "request" validators, including "required" configuration. Additionally nestjs-typebox will 57 // throw at bootup if parameters defined in the "request" validator config don't correspond 58 // with the parameters defined in the "path" configuration 59 async updatePet(id: number, data: Partial<Omit<Pet, 'id'>>) { 60 return this.petService.updatePet(id, data); 61 } 62 63 @HttpEndpoint({ 64 method: 'DELETE', 65 path: ':id', 66 validate: { 67 response: Type.Omit(PetSchema, ['microchip']), 68 request: [{ name: 'id', type: 'param', schema: Type.Number() }], 69 }, 70 }) 71 async deletePet(id: number) { 72 return this.petService.deletePet(id); 73 } 74}
Calling configure allows for the patching of the swagger plugin, custom
string formats (email, url, date, time, date-time, uuid), and support for errorMessage
overrides
within schema options.
1// main.ts 2 3import { Reflector } from '@nestjs/core'; 4import { configureNestJsTypebox } from 'nestjs-typebox'; 5 6configureNestJsTypebox({ 7 patchSwagger: true, 8 setFormats: true, 9}); 10 11async function bootstrap() { 12 const app = await NestFactory.create(AppModule); 13 14 await app.listen(3000); 15 console.log(`Application is running on: ${await app.getUrl()}`); 16} 17 18bootstrap();
Swagger patch derived from https://github.com/risenforces/nestjs-zod
No vulnerabilities found.
No security vulnerabilities found.