2023-08-18 22:56:39 +08:00
|
|
|
import type { Context, MiddlewareHandler, Env, ValidationTargets, TypedResponse } 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-08-18 22:56:39 +08:00
|
|
|
export type Hook<T, E extends Env, P extends string, O = {}> = (
|
2023-08-07 21:30:49 +08:00
|
|
|
result: { success: true; data: T } | { success: false; error: ZodError; data: T },
|
2023-03-21 17:24:29 +08:00
|
|
|
c: Context<E, P>
|
2023-08-19 01:36:55 +08:00
|
|
|
) => Response | Promise<Response> | void | Promise<Response | void> | TypedResponse<O>
|
2023-01-01 23:03:44 +08:00
|
|
|
|
2023-10-23 04:18:23 +08:00
|
|
|
type HasUndefined<T> = undefined extends T ? true : false
|
|
|
|
|
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,
|
2023-10-23 04:18:23 +08:00
|
|
|
I = z.input<T>,
|
|
|
|
O = z.output<T>,
|
2023-03-21 09:41:30 +08:00
|
|
|
V extends {
|
2023-12-13 16:31:25 +08:00
|
|
|
in: HasUndefined<I> extends true ? { [K in Target]?: I } : { [K in Target]: I }
|
|
|
|
out: { [K in Target]: O }
|
2023-03-21 09:41:30 +08:00
|
|
|
} = {
|
2023-12-13 16:31:25 +08:00
|
|
|
in: HasUndefined<I> extends true ? { [K in Target]?: I } : { [K in Target]: I }
|
|
|
|
out: { [K in Target]: O }
|
2023-03-21 09:41:30 +08:00
|
|
|
}
|
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-09-26 04:20:41 +08:00
|
|
|
validator(target, async (value, c) => {
|
|
|
|
const result = await schema.safeParseAsync(value)
|
2023-01-01 23:03:44 +08:00
|
|
|
|
|
|
|
if (hook) {
|
2023-08-07 21:30:49 +08:00
|
|
|
const hookResult = hook({ data: value, ...result }, c)
|
2023-08-18 23:15:03 +08:00
|
|
|
if (hookResult) {
|
|
|
|
if (hookResult instanceof Response || hookResult instanceof Promise) {
|
|
|
|
return hookResult
|
|
|
|
}
|
|
|
|
if ('response' in hookResult) {
|
|
|
|
return hookResult.response
|
|
|
|
}
|
2023-01-01 23:03:44 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!result.success) {
|
|
|
|
return c.json(result, 400)
|
|
|
|
}
|
|
|
|
|
|
|
|
const data = result.data as z.infer<T>
|
|
|
|
return data
|
|
|
|
})
|