zod-express-middleware icon indicating copy to clipboard operation
zod-express-middleware copied to clipboard

Transform single field

Open ivibumblebee opened this issue 2 years ago • 2 comments

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?

ivibumblebee avatar Oct 19 '22 16:10 ivibumblebee

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 avatar Oct 19 '22 19:10 DudeRandom21

@DudeRandom21 , That fixes the issue thanks!

samislam avatar Dec 24 '23 19:12 samislam