How do I prevent a client from sending an id in the UserUpdateDto. The User object contains an id (among other things) that I don’t want them to be able to update. However, despite what I’ve tried below, they can still pass an id in the body and that updates the property.
I’ve read that validationPipe does not work if you are using Prisma types because it needs the class-validator decorators. So I created the class UserUpdateDto for that purpose. Even if I remove the implements Pick<Prisma.UserUpdateInput, 'email' | 'name'>
(which I am doing to ensure the DTO remains in sync with the data model), it still allows an id through.
I’ve found that explicitly using @IsEmpty()
on the id field works, but it’s not ideal if there are multiple properties that I want to exclude.
export class UserUpdateDto
implements Pick<Prisma.UserUpdateInput, 'email' | 'name'>
{
@IsOptional()
@IsNotEmpty()
@IsEmail()
email?: string;
@IsOptional()
@IsNotEmpty()
@IsString()
name?: string;
// This works but I don't want to have to do this for every single unwanted property.
// @IsEmpty()
// id?: string;
}
async updateOne(params: {
where: Prisma.UserWhereUniqueInput;
data: UserUpdateDto;
}): Promise<User> {
const { where, data } = params;
return await this.prisma.user.update({ where, data });
}
@Patch('/:id')
async updateOne(
@Param('id') id: User['id'],
@Body() data: UserUpdateDto,
): Promise<boolean> {
await this.userService.updateOne({ where: { id }, data });
return true;
}
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({ logger: true }),
);
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000);
}
bootstrap();