2024-06-09 12:15:41 +08:00
|
|
|
import type { Context, Env, Input as HonoInput, MiddlewareHandler, ValidationTargets } from 'hono'
|
2023-07-30 07:07:44 +08:00
|
|
|
import { validator } from 'hono/validator'
|
2024-06-09 12:15:41 +08:00
|
|
|
import type { GenericSchema, GenericSchemaAsync, InferInput, InferOutput, SafeParseResult } from 'valibot'
|
2024-05-13 05:56:42 +08:00
|
|
|
import { safeParseAsync } from 'valibot'
|
2023-07-30 07:07:44 +08:00
|
|
|
|
2024-06-09 12:15:41 +08:00
|
|
|
type Hook<T extends GenericSchema | GenericSchemaAsync, E extends Env, P extends string> = (
|
2023-08-24 07:38:25 +08:00
|
|
|
result: SafeParseResult<T>,
|
2023-07-30 07:07:44 +08:00
|
|
|
c: Context<E, P>
|
2023-08-07 17:39:39 +08:00
|
|
|
) => Response | Promise<Response> | void | Promise<Response | void>
|
2023-07-30 07:07:44 +08:00
|
|
|
|
2024-02-15 04:38:43 +08:00
|
|
|
type HasUndefined<T> = undefined extends T ? true : false
|
|
|
|
|
2023-07-30 07:07:44 +08:00
|
|
|
export const vValidator = <
|
2024-06-09 12:15:41 +08:00
|
|
|
T extends GenericSchema | GenericSchemaAsync,
|
2023-07-30 07:07:44 +08:00
|
|
|
Target extends keyof ValidationTargets,
|
|
|
|
E extends Env,
|
|
|
|
P extends string,
|
2024-06-09 12:15:41 +08:00
|
|
|
In = InferInput<T>,
|
|
|
|
Out = InferOutput<T>,
|
2024-05-06 09:10:56 +08:00
|
|
|
I extends HonoInput = {
|
|
|
|
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-07-30 07:07:44 +08:00
|
|
|
>(
|
|
|
|
target: Target,
|
|
|
|
schema: T,
|
2023-08-24 07:38:25 +08:00
|
|
|
hook?: Hook<T, E, P>
|
2023-07-30 07:07:44 +08:00
|
|
|
): MiddlewareHandler<E, P, V> =>
|
2024-05-06 09:10:56 +08:00
|
|
|
// @ts-expect-error not typed well
|
2024-05-13 05:56:42 +08:00
|
|
|
validator(target, async (value, c) => {
|
|
|
|
const result = await safeParseAsync(schema, value)
|
2023-07-30 07:07:44 +08:00
|
|
|
|
|
|
|
if (hook) {
|
|
|
|
const hookResult = hook(result, c)
|
|
|
|
if (hookResult instanceof Response || hookResult instanceof Promise) {
|
|
|
|
return hookResult
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!result.success) {
|
|
|
|
return c.json(result, 400)
|
|
|
|
}
|
|
|
|
|
2024-06-09 12:15:41 +08:00
|
|
|
const data = result.output as InferOutput<T>
|
2023-07-30 07:07:44 +08:00
|
|
|
return data
|
|
|
|
})
|