import Route from 'route-parser'; import { HandlerInput, EngineFunction, RouteValues, EngineOutput, } from './types/handler'; import { NoHandlerFoundError } from './types/errors'; interface IRoute { route: Route; handler: EngineFunction; } export class Engine { name: string; description: string; domains: string[]; // eslint-disable-next-line @typescript-eslint/no-explicit-any routes: IRoute[] = []; constructor(name: string, description: string, domains: string[] = []) { this.domains = domains; this.name = name; this.description = description; } route( path: string, handler: EngineFunction ) { this.routes.push({ route: new Route(path), handler }); } async handle(input: HandlerInput): Promise { const url = new URL(input.url); const path = url.pathname + url.search + url.hash; for (const route of this.routes) { const match = route.route.match(path); if (match) { return await route.handler(input, { q: match, reverse: (req) => route.route.reverse(req), }); } } throw new NoHandlerFoundError(`${path}. [${this.name}]`); } }