Reputation: 55
I try to use a class-validator on a DTO to check if an id is valid or not.
Here is my controller:
@Get(':id')
async find(@Param('id') { id }: IdDto) {
try {
return await this.userService.findOne(id);
} catch (error) {}
}
and my Dto:
import { IsString, IsNotEmpty, IsMongoId } from 'class-validator';
import { Type, Transform } from 'class-transformer';
export class IdDto {
@IsMongoId()
id: string;
}
the prolem is when I try to search for a valid user, for example: http://localhost:3000/users/63ecf079c305ac977da87bcb
I got this error:
{
"statusCode": 400,
"message": [
"id must be a mongodb id"
],
"error": "Bad Request"
}
and I don't know why because it's a valid mongo id...
Can you help me please ?
And furthermore, I want to add a validation in my service:
async findOne(id: string): Promise<IUser | null> {
const user = await this.userModel.findById(id).exec();
if (user === null) {
throw new NotFoundException('No user found for this id');
}
return user;
}
I want to check if the user exists or not, if we look for a user (with a valid id) but there is no user, I want to throw an exception, and catch it in my controller. How can i do it correcly ? Thanks guys :)
Upvotes: 2
Views: 2344
Reputation: 146
Okay let me provide you with short and clear answer:
First, update your controller to use validation pipe with whitelist: true validation pipe option. It should fix the problem:
@Get(':id')
async find(@Param(new ValidationPipe({ whitelist: true })) { id }: IdDto) {
try {
return await this.answerService.findOne(id);
} catch (error) {}
}
Note: this will automatically remove non-whitelisted properties (those without any decorator in the validation class), refer to : https://docs.nestjs.com/techniques/validation#stripping-properties
Second, this article is helpful for you to decide how to handle the exception when no user is found.
Upvotes: 2