2023-01-01 23:03:44 +08:00
|
|
|
# Zod validator middleware for Hono
|
|
|
|
|
|
|
|
The validator middleware using [Zod](https://zod.dev) for [Hono](https://honojs.dev) applications.
|
|
|
|
You can write a schema with Zod and validate the incoming values.
|
|
|
|
|
|
|
|
## Usage
|
|
|
|
|
|
|
|
```ts
|
|
|
|
import { z } from 'zod'
|
2023-02-24 17:22:02 +08:00
|
|
|
import { zValidator } from '@hono/zod-validator'
|
2023-01-01 23:03:44 +08:00
|
|
|
|
|
|
|
const schema = z.object({
|
|
|
|
name: z.string(),
|
|
|
|
age: z.number(),
|
|
|
|
})
|
|
|
|
|
|
|
|
app.post('/author', zValidator('json', schema), (c) => {
|
2023-02-24 17:22:02 +08:00
|
|
|
const data = c.req.valid('json')
|
2023-01-01 23:03:44 +08:00
|
|
|
return c.json({
|
|
|
|
success: true,
|
|
|
|
message: `${data.name} is ${data.age}`,
|
|
|
|
})
|
|
|
|
})
|
|
|
|
```
|
|
|
|
|
2023-02-14 05:37:46 +08:00
|
|
|
Hook:
|
|
|
|
|
|
|
|
```ts
|
|
|
|
app.post(
|
|
|
|
'/post',
|
|
|
|
zValidator('json', schema, (result, c) => {
|
|
|
|
if (!result.success) {
|
|
|
|
return c.text('Invalid!', 400)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
//...
|
|
|
|
)
|
|
|
|
```
|
|
|
|
|
2024-12-25 09:32:07 +08:00
|
|
|
Throw Error:
|
|
|
|
|
|
|
|
throw a zod validate error instead of directly returning an error response.
|
|
|
|
|
|
|
|
```ts
|
|
|
|
// file: validator-wrapper.ts
|
|
|
|
import { ZodSchema } from "zod";
|
|
|
|
import type { ValidationTargets } from "hono";
|
|
|
|
import { zValidator as zv } from "@hono/zod-validator";
|
|
|
|
|
2025-01-05 17:04:45 +08:00
|
|
|
export const zValidator = <
|
|
|
|
T extends ZodSchema,
|
|
|
|
Target extends keyof ValidationTargets
|
|
|
|
>(
|
|
|
|
target: Target,
|
|
|
|
schema: T
|
|
|
|
) =>
|
|
|
|
zv(target, schema, (result, c) => {
|
|
|
|
if (!result.success) {
|
|
|
|
throw new HTTPException(400, { cause: result.error });
|
|
|
|
}
|
|
|
|
});
|
2024-12-25 09:32:07 +08:00
|
|
|
|
|
|
|
// usage
|
|
|
|
import { zValidator } from './validator-wrapper'
|
|
|
|
app.post(
|
|
|
|
'/post',
|
|
|
|
zValidator('json', schema)
|
|
|
|
//...
|
|
|
|
)
|
|
|
|
```
|
|
|
|
|
2023-01-01 23:03:44 +08:00
|
|
|
## Author
|
|
|
|
|
|
|
|
Yusuke Wada <https://github.com/yusukebe>
|
|
|
|
|
|
|
|
## License
|
|
|
|
|
|
|
|
MIT
|