turkerdev / fastify-type-provider-zod

MIT License
413 stars 25 forks source link

feat: support for transformations #102

Open gjuchault opened 2 months ago

gjuchault commented 2 months ago

This PR aims to solve the case where a zod schema that includes a transform would be provided

Before the changes

The res.send method would expect the z.infer of the schema (ie. the already transformed type), so the developer has to process the transform before (or there would be a typescript error) The serializerCompiler would parse again the data (and thus try to transform again), which can fail

After the change

When you provide a zod transformation, the type provider now asks the data to be the input (non-transformed), so the serializerCompiler is doing the transformation

Example on the provided test:

On the provided test, we reshape a subkey from a Date to string with toISOString(). Without the PR, res.send expects myDate to be a string, which fails at runtime (the transform throws: String.prototype.toISOString() is not a function). With the change, res.send expects a Date, which passes at runtime :)