This commit is contained in:
sianida26 2024-05-12 13:22:41 +07:00
parent b086d6d2a5
commit 3f6753d7d4

View File

@ -1,7 +1,33 @@
import { zValidator } from "@hono/zod-validator"; import { zValidator } from "@hono/zod-validator";
import DashboardError from "../errors/DashboardError"; import DashboardError from "../errors/DashboardError";
import type {
type ValidatorParameters = Parameters<typeof zValidator>; Context,
MiddlewareHandler,
Env,
ValidationTargets,
TypedResponse,
Input,
} from "hono";
import type { z, ZodError } from "zod";
export type Hook<T, E extends Env, P extends string, O = {}> = (
result:
| {
success: true;
data: T;
}
| {
success: false;
error: ZodError;
data: T;
},
c: Context<E, P>
) =>
| Response
| Promise<Response>
| void
| Promise<Response | void>
| TypedResponse<O>;
type HasUndefined<T> = undefined extends T ? true : false;
/** /**
* Creates a request validator using the Zod schema. * Creates a request validator using the Zod schema.
@ -12,11 +38,60 @@ type ValidatorParameters = Parameters<typeof zValidator>;
* the second is options for the Zod validator, and the third is a custom error handler. * the second is options for the Zod validator, and the third is a custom error handler.
* @returns A middleware function that validates the request against the provided schema. * @returns A middleware function that validates the request against the provided schema.
*/ */
const requestValidator = (...parameters: ValidatorParameters) => { function requestValidator<
T extends z.ZodType<any, z.ZodTypeDef, any>,
Target extends keyof ValidationTargets,
E extends Env,
P extends string,
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]
| undefined;
}
: {
[K2_1 in keyof In]: ValidationTargets[K][K2_1];
})
| undefined;
}
: {
[K_1 in Target]: K_1 extends "json"
? In
: HasUndefined<
keyof ValidationTargets[K_1]
> extends true
? {
[K2_2 in keyof In]?:
| ValidationTargets[K_1][K2_2]
| undefined;
}
: {
[K2_3 in keyof In]: ValidationTargets[K_1][K2_3];
};
};
out: { [K_2 in Target]: Out };
},
V extends I = I,
>(
target: Target,
schema: T,
hook?: Hook<z.TypeOf<T>, E, P, {}> | undefined
): MiddlewareHandler<E, P, V> {
//@ts-ignore
return zValidator( return zValidator(
parameters[0], target,
parameters[1], schema,
parameters[2] ?? hook ??
((result) => { ((result) => {
if (!result.success) { if (!result.success) {
let errors = result.error.flatten().fieldErrors as Record< let errors = result.error.flatten().fieldErrors as Record<
@ -38,6 +113,6 @@ const requestValidator = (...parameters: ValidatorParameters) => {
} }
}) })
); );
}; }
export default requestValidator; export default requestValidator;