UNPKG

exstack

Version:

A utility library designed to simplify and enhance express.js applications.

62 lines (61 loc) 1.91 kB
import { RequestHandler } from "express"; import * as z from "zod"; //#region src/zod.d.ts type Target = 'body' | 'query' | 'params' | 'all'; type Schema<T extends Target> = T extends 'all' ? { body?: z.ZodType; query?: z.ZodType; params?: z.ZodType; } : z.ZodType; declare class Validator { #private; all: (schema: Schema<"all">) => RequestHandler; body: (schema: z.ZodType) => RequestHandler; query: (schema: z.ZodType) => RequestHandler; params: (schema: z.ZodType) => RequestHandler; } declare const validator: Validator; declare module 'express-serve-static-core' { interface Request { /** * Retrieve already validated data. * * ### Examples * * ```ts * import { z } from 'zod'; * import { validator } from './validator'; * * // Define a schema for the body * const userSchema = z.object({ * name: z.string(), * age: z.number().int(), * }); * * // Use validator middleware * app.post('/user', validator.body(userSchema), (req, res) => { * // ✅ Inferred automatically from the Zod schema * const user = req.valid('body'); * // user: { name: string; age: number } * * // ✅ Explicitly specify Zod type if you prefer clarity * const typedUser = req.valid<typeof userSchema>('body'); * * // ✅ Or manually define your own structure * const manualUser = req.valid<{ name: string; age: number }>('body'); * * res.json(user); * }); * ``` */ valid<T extends Target>(type: T): T extends 'body' ? Record<string, any> : T extends 'query' ? Record<string, any> : T extends 'all' ? { body: Body; query: Query; params: Params; } : Record<string, any>; valid<T extends z.ZodType>(type: Target): z.Infer<T>; valid<T extends object>(type: Target): T; } } //#endregion export { validator };