itty-router
Version:
A tiny, zero-dependency router, designed to make beautiful APIs in any environment.
2 lines (1 loc) • 947 B
JavaScript
exports.Router=({base:r="",routes:e=[],...t}={})=>({__proto__:new Proxy({},{get:(t,a,o,c)=>(t,...l)=>e.push([a.toUpperCase?.(),RegExp(`^${(c=(r+t).replace(/\/+(\/|$)/g,"$1")).replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),l,c])&&o}),routes:e,...t,async fetch(r,...a){let o,c,l=new URL(r.url),p=r.query={__proto__:null};for(let[r,e]of l.searchParams)p[r]=p[r]?[].concat(p[r],e):e;r:try{for(let e of t.before||[])if(null!=(o=await e(r.proxy??r,...a)))break r;e:for(let[t,p,f,h]of e)if((t==r.method||"ALL"==t)&&(c=l.pathname.match(p))){r.params=c.groups||{},r.route=h;for(let e of f)if(null!=(o=await e(r.proxy??r,...a)))break e}}catch(e){if(!t.catch)throw e;o=await t.catch(e,r.proxy??r,...a)}try{for(let e of t.finally||[])o=await e(o,r.proxy??r,...a)??o}catch(e){if(!t.catch)throw e;o=await t.catch(e,r.proxy??r,...a)}return o}});
;