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.54 kB
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=s(require(`express`)),l=s(require(`zod/v3`)),u=s(require(`zod/v4/core`));function d(e){return`_zod`in e}function f(e,t){return d(e)?u.parse(e,t):e.parse(t)}function p(e,t){return d(e)?u.safeParse(e,t):e.safeParse(t)}function m(e){return e instanceof l.ZodError||typeof e==`object`&&!!e&&`issues`in e&&Array.isArray(e.issues)}var h=class{router;constructor(){this.router=c.default.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=f(e,t.body),r()}catch(e){m(e)?n.status(400).json({error:`Validation failed`,details:e.errors||e.issues}):r(e)}}}createQueryValidationMiddleware(e){return(t,n,r)=>{try{let n=f(e,t.query);Object.defineProperty(t,`query`,{value:n,writable:!1,enumerable:!0,configurable:!0}),r()}catch(e){m(e)?n.status(400).json({error:`Validation failed`,details:e.errors||e.issues}):r(e)}}}};function g(){return new h}function _(e){let t=new h;return e?.errorHandler&&t.getRouter().use(e.errorHandler),t}function v(...e){let t=new h;for(let n of e)t=t.useMiddleware(n);return t}exports.createTypedRouter=g,exports.createTypedRouterWithConfig=_,exports.createTypedRouterWithMiddleware=v,exports.isZod4Schema=d,exports.isZodError=m,exports.parseSchema=f,exports.safeParseSchema=p; //# sourceMappingURL=zod-router.cjs.map