2024-03-06 18:35:27 +08:00
|
|
|
import type { Context, MiddlewareHandler, Env, ValidationTargets, TypedResponse, Input } 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,
|
2024-03-06 18:35:27 +08:00
|
|
|
In = z.input<T>,
|
|
|
|
Out = z.output<T>,
|
|
|
|
I extends Input = {
|
|
|
|
in: HasUndefined<In> extends true
|
|
|
|
? {
|
|
|
|
[K in Target]?: K extends 'json'
|
|
|
|
? In
|
|
|
|
: HasUndefined<keyof ValidationTargets[K]> extends true
|
|
|
|
? { [K2 in keyof In]?: ValidationTargets[K][K2] }
|
|
|
|
: { [K2 in keyof In]: ValidationTargets[K][K2] }
|
|
|
|
}
|
|
|
|
: {
|
|
|
|
[K in Target]: K extends 'json'
|
|
|
|
? In
|
|
|
|
: HasUndefined<keyof ValidationTargets[K]> extends true
|
|
|
|
? { [K2 in keyof In]?: ValidationTargets[K][K2] }
|
|
|
|
: { [K2 in keyof In]: ValidationTargets[K][K2] }
|
|
|
|
}
|
|
|
|
out: { [K in Target]: Out }
|
|
|
|
},
|
|
|
|
V extends I = I
|
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> =>
|
2024-03-06 18:35:27 +08:00
|
|
|
// @ts-expect-error not typed well
|
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
|
|
|
|
})
|