import {WebsocketAppServer} from "../WebsocketAppServer"; import {IRouteConfig} from "../Services/IRouteConfig"; import {ClientRequest} from "../Request/ClientRequest"; import {IServiceHandlerConfig} from "../Services/IServiceHandlerConfig"; /** * Manages service routes and routes ClientRequests to service handlers */ export class RouteManager { private routes: Map = new Map(); constructor(public server: WebsocketAppServer) { this.monitorProcessedRequestStream(); } /** * Registers and array of route configrations * @param routeConfigs */ registerRoutes(routeConfigs: Array): void{ for (let routeConfig of routeConfigs) { this.register(routeConfig); } } getRouteConfig(path: string): IRouteConfig { if(this.routes.has(path)){ return this.routes.get(path); } console.error("Route with path <"+path+"> is not registered"); } getServiceHandlerConfig(path: string): IServiceHandlerConfig { if(this.routes.has(path)){ return this.routes.get(path).handler; } console.error("Route with path <"+path+"> is not registered"); } /** * Monitors processedRequestStream and triggers routing the request */ monitorProcessedRequestStream() { this.server.Request.processedRequestStream.subscribe({ next: (clientRequest: ClientRequest) => { this.routeRequest(clientRequest) } }) } /** * Routes a ClientRequest to route handler with matching service path * @param request * @returns {ServerResponse} */ routeRequest(request: ClientRequest) { if(this.routes.has(request.service)) { if(request.shouldRoute()) { console.log("Routing Request: " +request.service); this.routes.get(request.service).handler.handler(request); } } else{ console.error("Cannot route request. Route with path <"+request.service+"> is not registered"); } } /** * Registers a route configration * @param routeConfig */ register(routeConfig: IRouteConfig): void { if(this.routes.has(routeConfig.path)) { throw new Error("Service path: <"+routeConfig.path+"> has already been registered") } this.routes.set(routeConfig.path, routeConfig); } }