Skip to content

Commit

Permalink
add resolveRouterHandler helper
Browse files Browse the repository at this point in the history
  • Loading branch information
EthanThatOneKid committed Oct 17, 2023
1 parent 766d3a4 commit 89a7b84
Showing 1 changed file with 25 additions and 6 deletions.
31 changes: 25 additions & 6 deletions lib/router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ export class Router {
constructor(
public handlerMap: RouterHandlerMap = new Map(),
public readonly response404: ResponseResolvable = RESPONSE_404,
public readonly resonse5xx: ResponseResolvable | undefined = undefined,
) {}

/**
Expand Down Expand Up @@ -118,17 +119,19 @@ export class Router {
continue;
}

const url = new URL(request.url);
const params = Object.entries(match.pathname.groups)
.reduce((acc, [key, value]) => {
if (value) acc[key] = value;
return acc;
}, {} as { [key: string]: string });
return await handler.handle({
request,
url,
params,
});
return await resolveRouterHandler(handler, request, params)
.catch((error) => {
if (!(error instanceof Error) || !this.resonse5xx) {
throw error;
}

return resolveResponse(this.resonse5xx, request);
});
}

return await resolveResponse(this.response404, request);
Expand All @@ -148,3 +151,19 @@ export class Router {
);
}
}

/**
* resolveRouterHandler resolves a RouterHandler to a Response.
*/
async function resolveRouterHandler(
handler: RouterHandler,
request: Request,
params: Record<string, string>,
): Promise<Response> {
const url = new URL(request.url);
return await handler.handle({
request,
url,
params,
});
}

0 comments on commit 89a7b84

Please sign in to comment.