txtdot/packages/sdk/src/engine.ts

53 lines
1.3 KiB
TypeScript
Raw Normal View History

2024-05-12 16:24:50 +03:00
import Route from "route-parser";
import {
HandlerInput,
IHandlerOutput,
EngineFunction,
RouteValues,
} from "./types/handler";
import { NoHandlerFoundError } from "./types/errors";
interface IRoute<TParams extends RouteValues> {
route: Route;
handler: EngineFunction<TParams>;
}
export class Engine {
name: string;
description: string;
domains: string[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
routes: IRoute<any>[] = [];
constructor(name: string, description: string, domains: string[] = []) {
this.domains = domains;
this.name = name;
this.description = description;
}
route<TParams extends RouteValues>(
path: string,
handler: EngineFunction<TParams>
) {
this.routes.push({ route: new Route<TParams>(path), handler });
}
async handle(input: HandlerInput): Promise<IHandlerOutput> {
const url = new URL(input.getUrl());
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}]`);
}
}