2023-03-21 09:41:30 +08:00
|
|
|
import type { Context, MiddlewareHandler, Env, ValidationTargets } from 'hono'
|
2023-01-01 23:03:44 +08:00
|
|
|
import { validator } from 'hono/validator'
|
2023-05-11 21:03:08 +08:00
|
|
|
import type { z, ZodSchema, ZodError } from 'zod'
|
2023-01-01 23:03:44 +08:00
|
|
|
|
2023-03-21 17:24:29 +08:00
|
|
|
type Hook<T, E extends Env, P extends string> = (
|
2023-01-01 23:03:44 +08:00
|
|
|
result: { success: true; data: T } | { success: false; error: ZodError },
|
2023-03-21 17:24:29 +08:00
|
|
|
c: Context<E, P>
|
2023-08-07 17:39:29 +08:00
|
|
|
) => Response | Promise<Response> | void | Promise<Response | void>
|
2023-01-01 23:03:44 +08:00
|
|
|
|
2023-01-18 20:56:33 +08:00
|
|
|
export const zValidator = <
|
|
|
|
T extends ZodSchema,
|
2023-03-21 09:41:30 +08:00
|
|
|
Target extends keyof ValidationTargets,
|
2023-01-18 20:56:33 +08:00
|
|
|
E extends Env,
|
2023-03-21 09:41:30 +08:00
|
|
|
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> }
|
|
|
|
}
|
2023-01-18 20:56:33 +08:00
|
|
|
>(
|
2023-02-14 05:37:46 +08:00
|
|
|
target: Target,
|
2023-01-01 23:03:44 +08:00
|
|
|
schema: T,
|
2023-03-21 17:24:29 +08:00
|
|
|
hook?: Hook<z.infer<T>, E, P>
|
2023-03-21 09:41:30 +08:00
|
|
|
): MiddlewareHandler<E, P, V> =>
|
2023-02-14 05:37:46 +08:00
|
|
|
validator(target, (value, c) => {
|
2023-01-01 23:03:44 +08:00
|
|
|
const result = schema.safeParse(value)
|
|
|
|
|
|
|
|
if (hook) {
|
|
|
|
const hookResult = hook(result, c)
|
2023-03-21 09:41:30 +08:00
|
|
|
if (hookResult instanceof Response || hookResult instanceof Promise) {
|
2023-01-01 23:03:44 +08:00
|
|
|
return hookResult
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!result.success) {
|
|
|
|
return c.json(result, 400)
|
|
|
|
}
|
|
|
|
|
|
|
|
const data = result.data as z.infer<T>
|
|
|
|
return data
|
|
|
|
})
|