I'm creating an app with the nestjs framework using mongodb as my database. In my CRUD findOne method, I'd like to validate the ID being sent in is a Mongo ObjectID and return 400 if it's not (by default it returns 500 if you let it flow through). I can manually check this is, but is there a way to annotate the parameter to make this validation automatic?
@Get(':id')
findOne(@Param('id') id: string) {
return this.usersService.findOne(id);
}
CodePudding user response:
You can use class validator and transforms, like this:
Controller:
@Get(':id')
findOne(@Param() params: OnlyIDParamDTO) {
return this.usersService.findOne(params.id);
}
DTO:
export class OnlyIDParamDTO {
@ApiProperty({
description: 'Id',
required: true,
type: String,
default: '61d9cfbf17ed7311c4b3e485',
})
@IsMongoId()
@IsString()
@Transform((value) => SafeMongoIdTransform(value))
id: string;
}
Transforms:
export const SafeMongoIdTransform = ({ value }) => {
try {
if (
Types.ObjectId.isValid(value) &&
new Types.ObjectId(value).toString() === value
) {
return value;
}
throw new BadRequestException('Id validation fail');
} catch (error) {
throw new BadRequestException('Id validation fail');
}
};
You can read more here: https://docs.nestjs.com/pipes#object-schema-validation