Validate response objects

Using the zod validator middleware it is possible to validate params , query, request body like:
const route = app.post(
'/posts',
zValidator(
'form',
z.object({
body: z.string(),
})
),
(c) => {
// ...
return {
..
}
}
)
const route = app.post(
'/posts',
zValidator(
'form',
z.object({
body: z.string(),
})
),
(c) => {
// ...
return {
..
}
}
)
But is it also possible to validate the response object returned by the handler, to eg make sure response does contain required properties, but also does not include any unwanted properties?
3 Replies
ex0ns
ex0ns8mo ago
You can do this directly in the body of the handler can't you ? Before returning c.json(content) you could call returnSchema.parse(content) (where returnSchema is a zod schema)
Marcel Overdijk
Marcel OverdijkOP8mo ago
Yes that’s an option but the same could be said for parsing the request body. I wonder if it would be possible to use a global middleware, or – even better – to have a type safe return value..
Franquito
Franquito2mo ago
I second this, were you able to do it somehow? Or is it not possible
Want results from more Discord servers?
Add your server