h3
h3 copied to clipboard
feat(events): bodyValidator and queryValidator event arguments
🔗 Linked issue
unjs/nitro#2244
❓ Type of change
- [ ] 📖 Documentation (updates to the documentation, readme, or JSdoc annotations)
- [ ] 🐞 Bug fix (a non-breaking change that fixes an issue)
- [ ] 👌 Enhancement (improving an existing functionality like performance)
- [x] ✨ New feature (a non-breaking change that adds functionality)
- [ ] 🧹 Chore (updates to the build process or auxiliary tools and libraries)
- [ ] ⚠️ Breaking change (fix or feature that would cause existing functionality to change)
📚 Description
These changes introduce bodyValidator
and queryValidator
options to defineEventHandler
. These can be passed validation functions, such as a Zod schema's parse
method, to validate request bodies and query parameters and type them in the handler.
export default defineEventHandler({
bodyValidator: z.object({
id: z.string()
}).parse,
handler: async (event) => {
const { id } = await readBody(event);
// id is inferred as a string now
}
});
This will also allow Nitro to type the body
and query
options of $fetch
since the required types of the body and query can now be inferred from the event handler, opening the door to...
await $fetch('/foo', {
method: 'POST',
body: {}, // <-- body inferred as { id: string } from the Zod Schema, so this is a TS error
});
See the associated pull request to Nitro: unjs/nitro#2405
📝 Checklist
- [x] I have linked an issue or discussion.
- [ ] I have updated the documentation accordingly.