zod-express-middleware
zod-express-middleware copied to clipboard
Transform single field
In my query params, there is only one field I would like to modify, however if i define my schema in the form of the following:
export const schema= z.object({
field1: z.string(),
field2: z
.string()
.transform((data) => changeTypeToInteger(data)),
});
Then using processRequest
results in the field2
field in req.query
still being of the original type string
However if I define my schema in the form of the following:
export const schema= z.object({
field1: z.string(),
field2: z.string(),
})
.transform((data) => ({
...data,
field2: changeTypeToInteger(data.field2),
}));
Then the types are properly defined
I would like to be able to do nested transformations with processRequest
however it seems this is not currently supported?
Upon a bit of further evaluation it seems like there is a workaround of adding an idempotent transformation function to the end of the zod definition. Something like
export const schema = z
.object({
field1: z.string(),
field2: z.string().transform((data) => changeTypeToInteger(data)),
})
.transform((i) => i);
Which implies that the issue is that the transformed type isn't taken into account when the top level isn't a zodEffect
even if the internals of it are.
@DudeRandom21 , That fixes the issue thanks!