Aquila169 / zod-express-middleware

Express middleware to validate requests using zod schema's.
MIT License
82 stars 13 forks source link

Transform single field #7

Open ivibumblebee opened 1 year ago

ivibumblebee commented 1 year ago

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?

DudeRandom21 commented 1 year ago

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.

samislam commented 7 months ago

@DudeRandom21 , That fixes the issue thanks!