turkerdev / fastify-type-provider-zod

MIT License
337 stars 21 forks source link

Validation error serialization problem #21

Closed moeenn closed 1 year ago

moeenn commented 1 year ago

I am using fastify-type-provider-zod with Fastify (v 4.7.0).

I have defined a Login route and the body schema is defined as follows

z.object({
  email: z.string().email(),
  password: z.string(),
})

If the incoming request doesn't satisfy the zod schema, a validation error is thrown as expected. However the following response is received by the caller in case e.g. email is invalid.

{
  "statusCode": 400,
  "error": "Bad Request",
  "message": "[\n  {\n    \"validation\": \"email\",\n    \"code\": \"invalid_string\",\n    \"message\": \"Invalid email\",\n    \"path\": [\n      \"email\"\n    ]\n  }\n]"
}

Is there a way to fix the formatting of the response?

rupert-mckay commented 1 year ago

JSON.parse will correctly reconstruct the object

const errors = JSON.parse(response.message)

errors.forEach(({
  validation,
  code,
  message,
}) => {
  // do whatever you want with each error's properties
})
moeenn commented 1 year ago

Please guide me as to where i should put this code. A short example would be very helpful.

kibertoad commented 1 year ago

@moeenn fastify-type-provider-zod doesn't form your response, it only throws an error. Please take a look into fastify error handler customization in order to format your response properly: https://www.fastify.io/docs/latest/Reference/Server/#seterrorhandler

moeenn commented 1 year ago

Ok. Let me take a look.

kibertoad commented 1 year ago

That said, by default fastify should be forming proper JSON response already, it might be that the client which is consuming the API that is not deserializing it into an object correctly. In that case you'd need to use the code that @rupert-mckay has provided on your client side, after receiving the response.

moeenn commented 1 year ago

The response I posted above was received by Insomnia during my testing. I don't think this is a problem with Insomnia's JSON deserialization.

kibertoad commented 1 year ago

is response content-type set to application/json? if yes, then it's on client to deserialize