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
版权声明:本文标题:Zod validation pipe in NestJs controller try to validate all @Query parameters - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742403930a2468435.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论