-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.js
1 lines (1 loc) · 1.88 KB
/
mod.js
1
const b=n=>new Response("ERROR: "+n.message,{status:n.status||500}),H="application/json; charset=utf-8",O=n=>{const a=[];let e=-1;for(;(e=n.indexOf("/",e+1))!=-1&&(a.push(e),a.length!==3););return n.substring(a[2])};export function raptor({onError:n=b,on404:a=b.bind(null,{status:404,message:"404 not found"}),sub:e=!1}={}){const c={};let T=[];return{subs:[],resolve(p,t){const s=p;s.params={},s.conn=t||{};const u=s.path_url=O(s.url),R=u.indexOf("?"),q=R!==-1?u.substring(0,R):u;let l=[],o=c[s.method]||[],h=0;c.ANY&&(o=c.ANY.concat(o));for(const[d,i,x]of o)if(i.test(q)){x&&(s.params=i.exec(q).groups||{}),l=d;break}l=T.concat(l,[a]);const r=d=>{let i;try{i=d?n(d,s,r):l[h++](s,r)}catch(x){return d?n(x,s,r):r(x)}return i&&(i.then?i.then(void 0).catch(r):i)};return r()},make(p,...t){if(t=t.flat(),p==="WARE")return T=T.concat(t),this;if(p==="ERROR")return n=t[0],this;if(p==="404")return a=t[0],this;const s=p.indexOf("/"),u=s!==-1?p.substring(0,s):p,R=s!==-1?p.substring(s):"/";if(u==="ROUTER"){const q=R==="/"?"":R,l=[];for(let o=0;o<t.length;o++)if(typeof t[o]=="function"&&l.push(t[o]),typeof t[o]=="object")for(let h=0;h<t[o].subs.length;h++){const r=t[o].subs[h];r.fns=l.concat(r.fns),this.make(r.method+q+r.path,...r.fns)}return this}return e?this.subs.push({method:u,path:R,fns:t}):(c[u]=c[u]||[]).push([t,new RegExp(`^${R.replace(/\/$/,"").replace(/:(\w+)(\?)?(\.)?/g,"$2(?<$1>[^/]+)$2$3").replace(/(\/?)\*/g,"($1.*)?").replace(/\.(?=[\w(])/,"\\.")}/*$`),R.indexOf("/:")!==-1]),this},getRoute:()=>c,getWares:()=>T}}raptor.createRouter=()=>raptor({sub:!0});export class JsonResponse extends Response{constructor(a,e={}){e.headers?e.headers instanceof Headers?e.headers.set("content-type",H):e.headers["content-type"]=H:e.headers={"content-type":H},super(JSON.stringify(a),e)}}export class HttpError extends Error{constructor(a,e,c){super(e);this.message=e||"Http Error",this.status=a||500,this.name=c||"HttpError"}}