diff options
author | Alan Pearce | 2023-09-13 06:52:32 +0200 |
---|---|---|
committer | Alan Pearce | 2023-09-13 06:59:32 +0200 |
commit | c48a92fdd4d9ab9ec96c1cff73af84b9cdd1a96d (patch) | |
tree | 81b2eec287858c6461bfcaab7d04aad5ad4e8e67 /src | |
parent | 7c376d43ed17ffb44933f3ac8c1c8b8590dd675e (diff) | |
download | homestead-c48a92fdd4d9ab9ec96c1cff73af84b9cdd1a96d.tar.lz homestead-c48a92fdd4d9ab9ec96c1cff73af84b9cdd1a96d.tar.zst homestead-c48a92fdd4d9ab9ec96c1cff73af84b9cdd1a96d.zip |
Send 304 when file time not greater than if-modified-since header
Diffstat (limited to 'src')
-rw-r--r-- | src/index.ts | 18 |
1 files changed, 15 insertions, 3 deletions
diff --git a/src/index.ts b/src/index.ts index 8b8ab0b..790c856 100644 --- a/src/index.ts +++ b/src/index.ts @@ -15,7 +15,7 @@ type File = { filename: string; headers?: Record<string, string>; size: number; - mtime: string; + mtime: Date; }; let files = new Map<string, File>(); @@ -33,7 +33,7 @@ function registerFile(pathname: string, filename: string, stat: Stats): void { ? Object.assign({}, defaultHeaders, { "cache-control": "no-cache" }) : undefined, size: stat.size, - mtime: stat.mtime.toUTCString(), + mtime: stat.mtime, }); } @@ -67,7 +67,7 @@ async function serveFile( if (file && (await fsp.exists(file.filename))) { return new Response(Bun.file(file.filename), { headers: { - "last-modified": file.mtime, + "last-modified": file.mtime.toUTCString(), ...(file.headers || defaultHeaders), }, status: statusCode, @@ -77,10 +77,22 @@ async function serveFile( } } +function parseIfModifiedSinceHeader(header: string | null): number { + return header ? new Date(header).getTime() + 999 : 0; +} + export default withHtmlLiveReload({ fetch: async function (request) { const pathname = new URL(request.url).pathname; const file = files.get(pathname); + if (file) { + const ims = parseIfModifiedSinceHeader( + request.headers.get("if-modified-since"), + ); + if (ims >= file?.mtime.getTime()) { + return new Response("", { status: 304 }); + } + } return serveFile(file); }, }); |