admin管理员组

文章数量:1336134

I have implemented a validation pipe for Zod schema. However the issue is that if the controler has several @Query parameters, the Zod validation pipe is trying to validate all params and not only the one decoraterd with the pipe. In the following example, skip, take, comments and demandes params are submitted to the validation, but only skip, take should be.

When logging the value parameter in the transform function of the pipe, I can see that the 4 query parameters are send and this is a mistake...

the pipes in the contoller

@Get('/tickets')
  async getTickets(
    @Query(new ZodValidationPipe(paginationSchema, 'tickets'))
    pagination: TPaginationDTO,
    @Query('comments', new DefaultValuePipe(false), ParseBoolPipe)
    withComments: boolean = false,
    @Query('demandes', new DefaultValuePipe(false), ParseBoolPipe)
    withDemandes: boolean = false,
  )

the validation pipe:

export class ZodValidationPipe implements PipeTransform {
  constructor(
    private readonly zodSchema: ZodSchema,
    private readonly source: string = '',
  ) {}
  transform(value: any) {
    
    const parsedValue = zodSchema.safeParse(value);
    if (parsedValue.error) {
      throw new BadRequestException();
    } else {
      return parsedValue.data;
    }
  }
}

the schema TPaginationDTO

const paginationSchema = z
  .object({
    skip: zodInputStringToNumberPipe(
      z.number().positive().default(0),
    ).optional(),
    take: zodInputStringToNumberPipe(
      z
        .number()
        .positive()
        .default(Number(process.env.DEFAULT_PAGINATION_TAKE)),
    ).optional(),
  })
  .strict();

type TPaginationDTO = z.infer<typeof paginationSchema>;

url called : http://localhost:3000/app/tickets?take=9&comments=true&demandes=true

error, that shows that comments and demandes are tested against the pagination schema whereas it should not

" - unrecognized_keys - Unrecognized key(s) in object: 'comments', 'leonidemandes' "

the value received in the transform function is :

"{\"take\":\"9\",\"comments\":\"true\",\"demandes\":\"true\"}"

本文标签: Zod validation pipe in NestJs controller try to validate all Query parametersStack Overflow