refactor(zod-validator): refactor types (#69)

* refactor(zod-validator): refactor types

* add changeset
pull/70/head
Yusuke Wada 2023-03-21 10:41:30 +09:00 committed by GitHub
parent eb56625257
commit f263d58c87
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 13 deletions

View File

@ -0,0 +1,5 @@
---
'@hono/zod-validator': patch
---
patch: refactor types

View File

@ -1,34 +1,36 @@
import type { Context, MiddlewareHandler, Env } from 'hono' import type { Context, MiddlewareHandler, Env, ValidationTargets } from 'hono'
import { validator } from 'hono/validator' import { validator } from 'hono/validator'
import type { z } from 'zod' import type { z } from 'zod'
import type { ZodSchema, ZodError } from 'zod' import type { ZodSchema, ZodError } from 'zod'
type ValidationTargets = 'json' | 'form' | 'query' | 'queries' type Hook<T, E extends Env> = (
type Hook<T> = (
result: { success: true; data: T } | { success: false; error: ZodError }, result: { success: true; data: T } | { success: false; error: ZodError },
c: Context c: Context<E>
) => Response | Promise<Response> | void ) => Response | Promise<Response> | void
export const zValidator = < export const zValidator = <
T extends ZodSchema, T extends ZodSchema,
Target extends ValidationTargets, Target extends keyof ValidationTargets,
E extends Env, E extends Env,
P extends string P extends string,
V extends {
in: { [K in Target]: z.input<T> }
out: { [K in Target]: z.output<T> }
} = {
in: { [K in Target]: z.input<T> }
out: { [K in Target]: z.output<T> }
}
>( >(
target: Target, target: Target,
schema: T, schema: T,
hook?: Hook<z.infer<T>> hook?: Hook<z.infer<T>, E>
): MiddlewareHandler< ): MiddlewareHandler<E, P, V> =>
E,
P,
{ in: { [K in Target]: z.input<T> }; out: { [K in Target]: z.output<T> } }
> =>
validator(target, (value, c) => { validator(target, (value, c) => {
const result = schema.safeParse(value) const result = schema.safeParse(value)
if (hook) { if (hook) {
const hookResult = hook(result, c) const hookResult = hook(result, c)
if (hookResult instanceof Response || hookResult instanceof Promise<Response>) { if (hookResult instanceof Response || hookResult instanceof Promise) {
return hookResult return hookResult
} }
} }