refactor(zod-validator): rename `VaildatorTypes` to `ValidatoerTargets` (#46)

* refactor(zod-validator): rename `VaildatorTypes` to `ValidatoerTargets`

* add changeset
pull/47/head
Yusuke Wada 2023-02-14 06:37:46 +09:00 committed by GitHub
parent 95ca0fcad3
commit 72604c74da
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 24 additions and 7 deletions

View File

@ -0,0 +1,5 @@
---
'@hono/zod-validator': patch
---
refactor: rename `ValidationType` to `ValidationTargets`

View File

@ -1,7 +1,5 @@
# Zod validator middleware for Hono
**WIP**
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.
@ -25,6 +23,20 @@ app.post('/author', zValidator('json', schema), (c) => {
})
```
Hook:
```ts
app.post(
'/post',
zValidator('json', schema, (result, c) => {
if (!result.success) {
return c.text('Invalid!', 400)
}
})
//...
)
```
## Author
Yusuke Wada <https://github.com/yusukebe>

View File

@ -3,7 +3,7 @@ import { validator } from 'hono/validator'
import type { z } from 'zod'
import type { ZodSchema, ZodError } from 'zod'
type ValidationTypes = 'json' | 'form' | 'query' | 'queries'
type ValidationTargets = 'json' | 'form' | 'query' | 'queries'
type Hook<T> = (
result: { success: true; data: T } | { success: false; error: ZodError },
c: Context
@ -11,15 +11,15 @@ type Hook<T> = (
export const zValidator = <
T extends ZodSchema,
Type extends ValidationTypes,
Target extends ValidationTargets,
E extends Env,
P extends string
>(
type: Type,
target: Target,
schema: T,
hook?: Hook<z.infer<T>>
): MiddlewareHandler<E, P, { [K in Type]: z.infer<T> }> =>
validator(type, (value, c) => {
): MiddlewareHandler<E, P, { [K in Target]: z.infer<T> }> =>
validator(target, (value, c) => {
const result = schema.safeParse(value)
if (hook) {