Skip to content

Commit

Permalink
refactor(router): remove hard to understand logic
Browse files Browse the repository at this point in the history
  • Loading branch information
TomokiMiyauci committed Sep 11, 2022
1 parent 704228d commit 3cc15e0
Showing 1 changed file with 23 additions and 20 deletions.
43 changes: 23 additions & 20 deletions router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ export function createRouter(
): Router {
const routeMap = createRouteMap(routes, { withHead });

return createHandler(routeMap);
return (req) => resolveRequest(routeMap, req);
}

type RouteMap = Map<URLPattern, RouteHandler>;
Expand Down Expand Up @@ -168,28 +168,31 @@ function resolveHandlerLike(
return methods(methodHandler);
}

function createHandler(
async function resolveRequest(
routeMap: Iterable<[pattern: URLPattern, routeHandler: RouteHandler]>,
): Router {
return async (req) => {
for (const [pattern, handler] of routeMap) {
const { input: route = "", groups: params = {} } =
pattern.exec(req.url)?.pathname ?? {};

const ctx: RouteHandlerContext = { params, route, pattern };

try {
return await handler(req, ctx);
} catch {
return new Response(null, ResponseInit500);
}
req: Request,
): Promise<Response> {
for (const [pattern, handler] of routeMap) {
const result = pattern.exec(req.url);
if (!result) continue;

const ctx: RouteHandlerContext = {
params: result.pathname.groups,
route: result.pathname.input,
pattern,
};

try {
return await handler(req, ctx);
} catch {
return new Response(null, ResponseInit500);
}
}

return new Response(null, {
status: Status.NotFound,
statusText: STATUS_TEXT[Status.NotFound],
});
};
return new Response(null, {
status: Status.NotFound,
statusText: STATUS_TEXT[Status.NotFound],
});
}

function withHeadHandler(
Expand Down

0 comments on commit 3cc15e0

Please sign in to comment.