In following controller, in the GET call I intend to pass a boolean parameter.
@Controller('tests')
export class TestController {
constructor(private readonly testService: TestService) {}
@Get()
async getTests(@Query() params: QueryParamDto) {
return await this.testService.getTests(params.var);
}
}
and the Service method understands the type of params.var
as a boolean
.
@Injectable()
export class TestService {
@Get()
async getTests(var: boolean) {
return ...;
}
}
The QueryParamDto
looks like.
export class QueryParamDto {
@IsDefined()
@IsBoolean()
var: boolean;
}
I have defined a Global Validation Pipe in main.ts
.
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(
new ValidationPipe({
transform: true,
}),
);
await app.listen(3000);
}
bootstrap();
However, when I make a call to the endpoint /tests?var=true
it is unable to parse the var as a boolean and errors.
{
"statusCode": 400,
"message": [
"var must be a boolean value"
],
"error": "Bad Request"
}
My understanding is that app.useGlobalPipes(new ValidationPipe({transform: true...})
should automatically parse the params type as defined in the Dto, in this case var
as boolean
in QueryParamDto
.
CodePudding user response:
transform
means that the result of plainToClass
from class-transformer
will be the resulting parameter passed to your route handler. Normally this would be fine, but query and url parameters always come in as string
s, so you either need to add your own @Transform()
to make them get transformed properly, or use the transformOptions.enableImplicitConversion
option