txtdot/packages/sdk/src/engine.ts

53 lines
1.3 KiB
TypeScript
Raw Normal View History

2024-05-12 16:28:25 +03:00
import Route from 'route-parser';
2024-05-12 16:24:50 +03:00
import {
HandlerInput,
EngineFunction,
RouteValues,
2024-05-13 13:30:47 +03:00
EngineOutput,
2024-05-12 16:28:25 +03:00
} from './types/handler';
2024-05-12 16:24:50 +03:00
2024-05-12 16:28:25 +03:00
import { NoHandlerFoundError } from './types/errors';
2024-05-12 16:24:50 +03:00
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 });
}
2024-05-13 13:30:47 +03:00
async handle(input: HandlerInput): Promise<EngineOutput> {
2024-05-12 16:24:50 +03:00
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}]`);
}
}