This tutorial covers integrating class-validator and class-transformer for request validation in a NestJS application. It demonstrates setting up pino-http for structured system logging, abstracting the logger module into a shared library, and applying decorators to DTOs to enforce data integrity and prevent unauthorized property injection.
Length 10:31
Captions English (Generated), Spanish (Auto-translated), French (Auto-translated), Korean (Auto-translated), Portuguese (Auto-translated), Vietnamese (Auto-translated) #nestjs #validationpipe #pino-logger #class-validator #class-transformer #backend-development #software-engineering #coding-tutorial #api-testing #microservices
0:00 So we wanna add some validation to our newly created 0:03 controller so that we validate the user's input, which is always 0:07 best practice. So in order to add validation in our Nest 0:11 project, we're gonna pnpm install 0:14 class-validator and class-transformer. 0:19 I also want to enhance our logging right now, so I found this really 0:23 cool repository called nestjs-pinot, which is gonna 0:26 allow us to log every request and response in the 0:30 system automatically. And what's really great about it is 0:33 that it auto binds 0:34 request data to every log statement so that we can correlate 0:38 our logs out of the box without any additional 0:41 configuration. So we're gonna ahead and run pnpm install 0:46 nestjs-pinot and then 0:49 pinot-http as well. 0:53 And then we'll go ahead and run pnpm start dev to start up our 0:57 server again. 0:58 Now let's go back to our app here, and in our 1:02 reservations app, let's open up the main.ts folder. 1:07 So to add validation to our app, it's very easy. 1:10 All we have to do is call useGlobalPipes here on 1:14 our application. So validation is using 1:18 class-validator and class-transformer, which we can run 1:22 through as a NestJS pipe, which is essentially how NestJS 1:25 abstracts transformation of request data. 1:28 However, we can also validate request data 1:31 and reject the request if it 1:32 doesn't meet our validation. So we're gonna call new 1:35 ValidationPipe here and import this from NestJS 1:39 Common. Now, to add that Pinot logger that we installed 1:43 earlier as well, we're gonna call 1:45 app.useLogger. And then we're gonna call in 1:49 app.get, which is going to grab 1:53 the logger here, which we're gonna go ahead and actually 1:56 import up top manually. We're gonna import 2:00 Logger here from nestjs-pinot. 2:04 And now, importantly, we need to go to our reservations.module, 2:09 and we will need to 2:11 import the LoggerModule 2:15 from nestjs-pinot and call forRoot on that logger
The rest of the transcript is for members.
Sign in