2024-10-19 16:35:44 -06:00

73 lines
1.8 KiB
TypeScript

export class Router {
private routes: Map<string, Handler[]> = new Map();
public route(route: string) {
const methods: Record<string, Handler> = {
get: () => undefined,
post: () => undefined,
put: () => undefined,
delete: () => undefined,
};
this.routes.set(route, this.routes.get(route) || []);
this.routes.get(route)?.push((r, c) => {
switch (r.method) {
case "GET":
return methods.get?.(r, c);
case "POST":
return methods.post?.(r, c);
case "PUT":
return methods.put?.(r, c);
case "DELETE":
return methods.delete?.(r, c);
default:
return undefined;
}
});
return {
get(handler: Handler) {
methods.get = handler;
return this;
},
post(handler: Handler) {
methods.post = handler;
return this;
},
put(handler: Handler) {
methods.put = handler;
return this;
},
delete(handler: Handler) {
methods.delete = handler;
return this;
},
};
}
public handle = async (req: Request): Promise<Response> => {
const url = new URL(req.url);
for (const [route, handlers] of this.routes.entries()) {
const pattern = new URLPattern({ pathname: route });
const match = pattern.exec(req.url);
if (match) {
let res;
for (const handler of handlers) {
res = await handler(req, {
url,
state: {},
params: match.pathname.groups,
});
if (res) {
return res;
}
}
}
}
return new Response("Not found", { status: 404 });
};
}
export type Handler = (
req: Request,
ctx: Context,
) => Promise<Response | undefined> | Response | undefined;