UNPKG

@minisylar/express-typed-router

Version:

A strongly-typed Express router with Zod validation and automatic type inference for params, body, query, and middleware

2 lines 2.03 kB
import e from"express";import*as t from"zod/v3";import*as n from"zod/v4/core";function r(e){return`_zod`in e}function i(e,t){return r(e)?n.parse(e,t):e.parse(t)}function a(e,t){return r(e)?n.safeParse(e,t):e.safeParse(t)}function o(e){return e instanceof t.ZodError||typeof e==`object`&&!!e&&`issues`in e&&Array.isArray(e.issues)}var s=class{router;constructor(){this.router=e.Router()}useMiddleware(e){return this.router.use(e),this}getRouter(){return this.router}get(e,t,n){return this.registerRoute(`get`,e,t,n)}post(e,t,n){return this.registerRoute(`post`,e,t,n)}put(e,t,n){return this.registerRoute(`put`,e,t,n)}patch(e,t,n){return this.registerRoute(`patch`,e,t,n)}delete(e,t,n){return this.registerRoute(`delete`,e,t,n)}options(e,t,n){return this.registerRoute(`options`,e,t,n)}head(e,t,n){return this.registerRoute(`head`,e,t,n)}all(e,t,n){return this.registerRoute(`all`,e,t,n)}registerRoute(e,t,n,r){let i=[];if(typeof n==`object`){let e=n;e.middleware&&i.push(...e.middleware),e.bodySchema&&i.push(this.createBodyValidationMiddleware(e.bodySchema)),e.querySchema&&i.push(this.createQueryValidationMiddleware(e.querySchema)),i.push(r)}else i.push(n);return this.router[e](t,...i),this}createBodyValidationMiddleware(e){return(t,n,r)=>{try{t.body=i(e,t.body),r()}catch(e){o(e)?n.status(400).json({error:`Validation failed`,details:e.errors||e.issues}):r(e)}}}createQueryValidationMiddleware(e){return(t,n,r)=>{try{let n=i(e,t.query);Object.defineProperty(t,`query`,{value:n,writable:!1,enumerable:!0,configurable:!0}),r()}catch(e){o(e)?n.status(400).json({error:`Validation failed`,details:e.errors||e.issues}):r(e)}}}};function c(){return new s}function l(e){let t=new s;return e?.errorHandler&&t.getRouter().use(e.errorHandler),t}function u(...e){let t=new s;for(let n of e)t=t.useMiddleware(n);return t}export{c as createTypedRouter,l as createTypedRouterWithConfig,u as createTypedRouterWithMiddleware,r as isZod4Schema,o as isZodError,i as parseSchema,a as safeParseSchema}; //# sourceMappingURL=zod-router.js.map