Skip to content

Commit

Permalink
refactor(@remix-run/deno): throw custom error when static files are n…
Browse files Browse the repository at this point in the history
…ot found

so that `createRequestHandlerWithStaticFiles` is more portable across runtimes and adapters
  • Loading branch information
pcattori committed May 11, 2022
1 parent 9e3b2b9 commit 9e4e995
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions packages/remix-deno/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ export function createRequestHandler<Context = unknown>({
};
}

class StaticFileNotFoundError extends Error {
constructor(message: string) {
super(message);
}
}

export async function serveStaticFiles(
request: Request,
{
Expand Down Expand Up @@ -64,9 +70,18 @@ export async function serveStaticFiles(
headers.set("Cache-Control", defaultCacheControl(url, assetsPublicPath));
}

const file = await Deno.readFile(path.join(publicDir, url.pathname));

return new Response(file, { headers });
const filePath = path.join(publicDir, url.pathname);
try {
const file = await Deno.readFile(filePath);
return new Response(file, { headers });
} catch (error) {
if (error.code === "EISDIR" || error.code === "ENOENT") {
throw new StaticFileNotFoundError(
`No such file or directory: ${filePath}`,
);
}
throw error;
}
}

export function createRequestHandlerWithStaticFiles<Context = unknown>({
Expand All @@ -93,7 +108,7 @@ export function createRequestHandlerWithStaticFiles<Context = unknown>({
try {
return await serveStaticFiles(request, staticFiles);
} catch (error) {
if (error.code !== "EISDIR" && error.code !== "ENOENT") {
if (!(error instanceof StaticFileNotFoundError)) {
throw error;
}
}
Expand Down

0 comments on commit 9e4e995

Please sign in to comment.