add basic routing support

This commit is contained in:
Kaan Barmore-Genç 2022-05-22 00:33:51 -04:00
parent 82b2c46e98
commit 29bd394ebe
2 changed files with 51 additions and 8 deletions

View File

@ -1,17 +1,38 @@
import { endpoint } from "../src";
import { startServer } from "../src/core/server";
import { route } from "../src/routing/router";
type Data = {
name: string;
};
startServer(
endpoint<void, Data>(async (req) => {
return {
status: 200,
body: {
name: "foo",
endpoint<void, Data>(
route([
{
app: async (req) => {
return {
status: 200,
body: {
name: "foo",
},
};
},
method: "GET",
url: "/",
},
};
}),
{
app: async (req) => {
return {
status: 200,
body: {
name: "polo",
},
};
},
method: "GET",
url: "/marco",
},
]),
),
);

View File

@ -1 +1,23 @@
export {};
import type { Server } from "../compose";
import type { BufferedResponse, Request } from "../core/bufferedServer";
export type Route<ReqData extends Request, ResData> = {
method: string;
url: string;
app: Server<ReqData, ResData>;
};
export function route<ReqData extends Request, ResData>(
routes: Route<ReqData, ResData>[],
): Server<ReqData, ResData> {
return async function route_(request) {
const { url, method } = request;
const route = routes.filter(
(registered) => registered.url === url && registered.method === method,
)[0];
if (route) {
return route.app(request);
}
throw "No routes matched";
};
}