refactor(zod-validator): refactor types (#69)
* refactor(zod-validator): refactor types * add changesetpull/70/head
parent
eb56625257
commit
f263d58c87
|
@ -0,0 +1,5 @@
|
||||||
|
---
|
||||||
|
'@hono/zod-validator': patch
|
||||||
|
---
|
||||||
|
|
||||||
|
patch: refactor types
|
|
@ -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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue