add basic routing support
This commit is contained in:
parent
82b2c46e98
commit
29bd394ebe
|
@ -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",
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
|
|
@ -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";
|
||||
};
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue