Skip to content

Commit

Permalink
Fix: Safely bail from unhandled requests
Browse files Browse the repository at this point in the history
  • Loading branch information
TheCommieAxolotl committed Aug 1, 2023
1 parent 41cc0fe commit 58efabd
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions src/router/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ import { App } from "../types";
export { route } from "./route";
import { Route } from "./route";

const bail = (response: ServerResponse<IncomingMessage>, status: number) => {
response.statusCode = status;
response.end();
};

const matchRoute = (req: IncomingMessage, route: Route): boolean => {
const pathParts = req.url.split("/");
const routeParts = route.path.split("/");
Expand All @@ -19,7 +24,19 @@ const matchRoute = (req: IncomingMessage, route: Route): boolean => {
methodMatches = false;
}

if (!route.path.includes("[...") && pathParts.length !== routeParts.length) {
pathMatches = false;

return pathMatches && methodMatches;
}

for (let i = 0; i < pathParts.length; i++) {
if (routeParts[i] === undefined) {
pathMatches = false;

break;
}

if (routeParts[i].startsWith("[...") && routeParts[i].endsWith("]")) {
pathMatches = true;
break;
Expand Down Expand Up @@ -86,7 +103,7 @@ export const handleRequest = async (
) => {
const route = Array.from(app._routes).find((route) => matchRoute(request, route));

if (!route) return;
if (!route) return bail(response, 404);

const responseData = await route.handler({
request,
Expand All @@ -96,7 +113,7 @@ export const handleRequest = async (
method: request.method.toLowerCase() as Parameters<Route["handler"]>[0]["method"],
});

if (!responseData) return;
if (!responseData) return bail(response, 500);

if (responseData.headers) {
for (const [key, value] of Object.entries(responseData.headers)) {
Expand Down

0 comments on commit 58efabd

Please sign in to comment.