Skip to content

Instantly share code, notes, and snippets.

@dylangrijalva
Created June 26, 2025 02:00
Show Gist options
  • Save dylangrijalva/b161d96698f5b187f3cb038c0b75e5b5 to your computer and use it in GitHub Desktop.
Save dylangrijalva/b161d96698f5b187f3cb038c0b75e5b5 to your computer and use it in GitHub Desktop.
Parses and validates the incoming JSON request body using the specified schema.
import { getContext } from "hono/context-storage";
import type z from "zod";
import { SignInRequest } from "../features/auth/sign-in-handler";
import { SignUpRequest } from "../services/auth/auth-service";
import type { SoEasyEnv } from "../types";
export const Schemas = {
signIn: SignInRequest.schema,
signUp: SignUpRequest.schema,
} as const;
type SchemaMap = typeof Schemas;
type SchemaKey = keyof SchemaMap;
type SchemaOutput<K extends SchemaKey> = z.infer<SchemaMap[K]>;
/**
* Parses and validates the incoming JSON request body using the specified schema.
*
* @template K - The key of the schema to use for validation.
* @param schemaName - The name of the schema to use for parsing and validation.
* @returns A promise that resolves to the parsed and validated data conforming to the specified schema.
* @throws If the request body does not conform to the schema.
*/
export async function useRequest<K extends SchemaKey>(schemaName: K): Promise<SchemaOutput<K>> {
const data = await getContext<SoEasyEnv>().req.json();
const schema = Schemas[schemaName];
return schema.parse(data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment