edge-master
Version:
A Micro Framework for Edges
2 lines (1 loc) • 1.51 kB
JavaScript
;import{InterceptorType as o}from"./types/interceptor";export class EdgeController{constructor(){this._reqInterceptors=[],this._hasReqInterceptor=!1,this._resInterceptors=[],this._hasResInterceptor=!1,this._routes=[]}async interceptRequest(e){if(!this._hasReqInterceptor)return e.reqCtx.req;let r=new Request(e.reqCtx.req);for(const t of this._reqInterceptors)try{r=await t.intercept({...e,reqCtx:{...e.reqCtx,req:r}})}catch(s){throw console.error(`Request interceptor error: ${s}`),s}return r}async interceptResponse(e){if(!this._hasResInterceptor)return e.res;let r=e.res;for(const t of this._resInterceptors)try{r=await t.intercept({...e,res:r})}catch(s){throw console.error(`Response interceptor error: ${s}`),s}return r}async handleRoutes(e){const r=this._routes.find(t=>t.matcher(e.req));if(r)return r.routeHandler.execute(e);throw new Error("There is no route maches related to this request")}addRoute(e,r){return this._routes.push({matcher:e,routeHandler:r}),this}addInterceptor(e){return e.type===o.Request&&(this._reqInterceptors.push(e),this._hasReqInterceptor||(this._hasReqInterceptor=!0)),e.type===o.Response&&(this._resInterceptors.push(e),this._hasResInterceptor||(this._hasResInterceptor=!0)),this}async handleRequest(e){return new Promise(async r=>{try{r(await this.interceptResponse({reqCtx:e,responder:r,res:await this.handleRoutes({req:await this.interceptRequest({reqCtx:e,responder:r}),reqCtx:e,responder:r})}))}catch{r(new Response("Internal Server Error",{status:500}))}})}}