Complete the code to apply a built-in validation pipe to the controller method.
import { Controller, Post, Body, [1] } from '@nestjs/common'; @Controller('users') export class UsersController { @Post() createUser(@Body(new [1]()) userData: any) { return userData; } }
The ValidationPipe is used to automatically validate and transform incoming data in NestJS controllers.
Complete the code to transform the input string to a number using a pipe.
import { Controller, Get, Param, [1] } from '@nestjs/common'; @Controller('items') export class ItemsController { @Get(':id') getItem(@Param('id', new [1]()) id: number) { return { id }; } }
The ParseIntPipe converts the input string parameter to a number, ensuring the controller receives a number type.
Fix the error in the pipe usage to enable automatic transformation of input data.
import { Controller, Post, Body, ValidationPipe } from '@nestjs/common'; @Controller('products') export class ProductsController { @Post() addProduct(@Body(new ValidationPipe({ [1]: true })) productData: any) { return productData; } }
The transform option enables automatic conversion of input data types in ValidationPipe.
Fill both blanks to create a custom pipe that validates and transforms input.
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common'; @Injectable() export class [1] implements PipeTransform { transform(value: any, metadata: ArgumentMetadata) { if (typeof value !== '[2]') { throw new BadRequestException('Validation failed'); } return value; } }
This custom pipe named StringValidationPipe checks if the input is a string and throws an error if not.
Fill all three blanks to apply a global validation pipe with transformation enabled.
import { ValidationPipe, [1] } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalPipes(new [2]({ [3]: true })); await app.listen(3000); } bootstrap();
This code imports INestApplication, applies a global ValidationPipe with the transform option enabled to automatically convert input types.