UNPKG

itty-router

Version:

A tiny, zero-dependency router, designed to make beautiful APIs in any environment.

2 lines (1 loc) 947 B
const r=({base:r="",routes:e=[],...a}={})=>({__proto__:new Proxy({},{get:(a,t,o,c)=>(a,...l)=>e.push([t.toUpperCase?.(),RegExp(`^${(c=(r+a).replace(/\/+(\/|$)/g,"$1")).replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),l,c])&&o}),routes:e,...a,async fetch(r,...t){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 a.before||[])if(null!=(o=await e(r.proxy??r,...t)))break r;e:for(let[a,p,f,h]of e)if((a==r.method||"ALL"==a)&&(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,...t)))break e}}catch(e){if(!a.catch)throw e;o=await a.catch(e,r.proxy??r,...t)}try{for(let e of a.finally||[])o=await e(o,r.proxy??r,...t)??o}catch(e){if(!a.catch)throw e;o=await a.catch(e,r.proxy??r,...t)}return o}});export{r as Router};