Skip to content

Instantly share code, notes, and snippets.

@brookback
Created February 21, 2024 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brookback/2b0db5ca1561ec69d8d23e8278e0944a to your computer and use it in GitHub Desktop.
Save brookback/2b0db5ca1561ec69d8d23e8278e0944a to your computer and use it in GitHub Desktop.
Super simple URLPattern based router.
interface Route {
pattern: URLPattern;
handler: Handler;
options: {
method: Method;
};
}
export type Handler = (req: Request) => Promise<Response> | Response;
interface Match {
params: Record<string, string | undefined>;
query: URLSearchParams;
handler: Handler;
}
type Method = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'ALL';
export class Router {
private routes: Array<Route> = [];
route(method: Method, pathname: string, handler: Handler) {
this.routes.push({
handler,
pattern: new URLPattern({ pathname }),
options: {
method,
},
});
}
match(url: string, method: string): Match | null {
for (const route of this.routes) {
const { pattern, handler, options } = route;
if (options.method != method) continue; // No match
const match = pattern.exec(url);
if (match) {
return { handler, params: match.pathname.groups, query: new URLSearchParams(match.search.input) };
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment