feat: add support for route groups (#1563)

This commit is contained in:
Marvin Hagemeister
2023-08-02 09:51:20 +02:00
committed by GitHub
parent 4b28e2e269
commit e4d797ae4e
17 changed files with 384 additions and 218 deletions
+12 -5
View File
@@ -1,4 +1,4 @@
import { ServeHandlerInfo } from "./types.ts";
import { BaseRoute, ErrorHandlerContext, ServeHandlerInfo } from "./types.ts";
type HandlerContext<T = unknown> = T & ServeHandlerInfo;
@@ -37,13 +37,19 @@ export type MatchHandler<T = unknown> = (
// deno-lint-ignore ban-types
export interface Routes<T = {}> {
[key: string]: { [K in KnownMethod | "default"]?: MatchHandler<T> };
[key: string]: {
baseRoute: BaseRoute;
methods: {
[K in KnownMethod | "default"]?: MatchHandler<T>;
};
};
}
export type DestinationKind = "internal" | "static" | "route" | "notFound";
// deno-lint-ignore ban-types
export type InternalRoute<T = {}> = {
baseRoute: BaseRoute;
pattern: URLPattern;
methods: { [K in KnownMethod]?: MatchHandler<T> };
default?: MatchHandler<T>;
@@ -79,7 +85,7 @@ export function defaultOtherHandler(_req: Request): Response {
export function defaultErrorHandler(
_req: Request,
_ctx: HandlerContext,
_ctx: ErrorHandlerContext,
err: unknown,
): Response {
console.error(err);
@@ -107,15 +113,16 @@ function processRoutes<T>(
routes: Routes<T>,
destination: DestinationKind,
) {
for (const [path, methods] of Object.entries(routes)) {
for (const [path, def] of Object.entries(routes)) {
const entry: InternalRoute<T> = {
baseRoute: def.baseRoute,
pattern: new URLPattern({ pathname: path }),
methods: {},
default: undefined,
destination,
};
for (const [method, handler] of Object.entries(methods)) {
for (const [method, handler] of Object.entries(def.methods)) {
if (method === "default") {
entry.default = handler;
} else if (knownMethods.includes(method as KnownMethod)) {