2023-01-18 20:56:33 +08:00
|
|
|
import type { Context, MiddlewareHandler, Env } from 'hono'
|
2023-01-01 23:03:44 +08:00
|
|
|
import { validator } from 'hono/validator'
|
|
|
|
import type { z } from 'zod'
|
|
|
|
import type { ZodSchema, ZodError } from 'zod'
|
|
|
|
|
2023-02-14 05:37:46 +08:00
|
|
|
type ValidationTargets = 'json' | 'form' | 'query' | 'queries'
|
2023-01-01 23:03:44 +08:00
|
|
|
type Hook<T> = (
|
|
|
|
result: { success: true; data: T } | { success: false; error: ZodError },
|
|
|
|
c: Context
|
|
|
|
) => Response | Promise<Response> | void
|
|
|
|
|
2023-01-18 20:56:33 +08:00
|
|
|
export const zValidator = <
|
|
|
|
T extends ZodSchema,
|
2023-02-14 05:37:46 +08:00
|
|
|
Target extends ValidationTargets,
|
2023-01-18 20:56:33 +08:00
|
|
|
E extends Env,
|
|
|
|
P extends string
|
|
|
|
>(
|
2023-02-14 05:37:46 +08:00
|
|
|
target: Target,
|
2023-01-01 23:03:44 +08:00
|
|
|
schema: T,
|
|
|
|
hook?: Hook<z.infer<T>>
|
2023-03-17 16:02:15 +08:00
|
|
|
): MiddlewareHandler<
|
|
|
|
E,
|
|
|
|
P,
|
|
|
|
{ in: { [K in Target]: z.input<T> }; out: { [K in Target]: z.output<T> } }
|
|
|
|
> =>
|
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)
|
|
|
|
if (hookResult instanceof Response || hookResult instanceof Promise<Response>) {
|
|
|
|
return hookResult
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!result.success) {
|
|
|
|
return c.json(result, 400)
|
|
|
|
}
|
|
|
|
|
|
|
|
const data = result.data as z.infer<T>
|
|
|
|
return data
|
|
|
|
})
|