Initial commit
This commit is contained in:
30
src/util/validators.ts
Normal file
30
src/util/validators.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import type { MiddlewareHandler } from "@hono/hono";
|
||||
import { z } from "zod";
|
||||
import type { HonoEnv } from "./types.ts";
|
||||
|
||||
// thanks claude, this hurt my brain!
|
||||
export const typedZValidator = <T extends z.ZodSchema>(
|
||||
target: 'query' | 'json' | 'form' | 'header' | 'param' | 'cookie',
|
||||
schema: T
|
||||
) => {
|
||||
return zValidator(target, schema) as MiddlewareHandler<
|
||||
HonoEnv,
|
||||
string,
|
||||
{
|
||||
in: { [K in typeof target]: z.input<T> };
|
||||
out: { [K in typeof target]: z.output<T> };
|
||||
}
|
||||
>;
|
||||
};
|
||||
|
||||
export const transformStringToEnum = <T>(anEnum: { [s: number]: string }) => {
|
||||
return (arg: string, ctx: z.RefinementCtx<string>) => {
|
||||
const int = parseInt(arg);
|
||||
if (isNaN(int)) ctx.addIssue("Must be parseable as a number");
|
||||
else {
|
||||
if (anEnum[int]) return int as T;
|
||||
else ctx.addIssue("Number must be a valid enum member");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user