all repos — archive/homestead @ 14e6b232704e9358a2df181b2db0858f794f67de

My future indieweb platform

Return 404 if file no longer exists

Alan Pearce
commit

14e6b232704e9358a2df181b2db0858f794f67de

parent

817164e34248c559d4a883bf991e48407111473a

1 file changed, 17 insertions(+), 14 deletions(-)

jump to
M src/index.tssrc/index.ts
@@ -19,6 +19,7 @@ }
type File = { filename: string; + headers: Record<string, string>; size: number; mtime: string; };
@@ -33,6 +34,10 @@ console.warn("File already registered:", pathname);
} files.set(pathname, { filename: absPath, + headers: + pathname === "/404.html" + ? Object.assign({}, defaultHeaders, { "cache-control": "no-cache" }) + : defaultHeaders, size: stat.size, mtime: stat.mtime.toUTCString(), });
@@ -60,24 +65,22 @@ }
} walkDirectory(publicDir, ""); + +async function serveFile(file: File | undefined): Promise<Response> { + if (file && (await fsp.exists(file.filename))) { + return new Response(Bun.file(file.filename), { + headers: file.headers, + status: 200, + }); + } else { + return serveFile(files.get("/404.html")); + } +} export default withHtmlLiveReload({ fetch: async function (request) { const pathname = new URL(request.url).pathname; const file = files.get(pathname); - if (file) { - return new Response(Bun.file(file.filename), { - headers: defaultHeaders, - status: 200, - }); - } - - return new Response(Bun.file(getFilename("404.html")), { - headers: Object.assign({}, defaultHeaders, { - "cache-control": "max-age=5, no-cache", - }), - status: 404, - statusText: "Not Found", - }); + return serveFile(file); }, });