Skip to content

Commit 978b57e

Browse files
authored
feat: Check max-age in Cache-Control header for freshness (#50)
* feat: Check `max-age` in `Cache-Control` header for freshness * chore: Update Changesets
1 parent 01ac1e7 commit 978b57e

2 files changed

Lines changed: 16 additions & 8 deletions

File tree

‎.changeset/weak-pets-rescue.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@foxify/fresh": minor
3+
---
4+
5+
Check `max-age` in `Cache-Control` header for freshness

‎packages/fresh/src/index.ts‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@ import { IncomingHttpHeaders, OutgoingHttpHeaders } from "node:http";
22

33
/**
44
* RegExp to check for no-cache token in Cache-Control.
5+
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#max-age_2
56
* @private
67
*/
7-
const CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/;
8+
const CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?(?:no-cache|max-age=0)\s*?(?:,|$)/;
89

910
/**
1011
* Parse an HTTP Date into a number.
@@ -28,25 +29,30 @@ function compareETags(etag: string, str: string): boolean {
2829
* @private
2930
*/
3031
function isStale(etag: string, noneMatch: string): boolean {
32+
const length = noneMatch.length;
3133
let start = 0;
3234
let end = 0;
3335

34-
for (let i = 0, len = noneMatch.length; i < len; i++) {
36+
for (let i = 0; i < length; i++) {
3537
switch (noneMatch.charCodeAt(i)) {
3638
case 0x20: /* */
3739
if (start === end) start = end = i + 1;
40+
3841
break;
3942
case 0x2c: /* , */
40-
if (compareETags(etag, noneMatch.substring(start, end))) return false;
43+
if (compareETags(etag, noneMatch.slice(start, end))) return false;
44+
4145
start = end = i + 1;
46+
4247
break;
4348
default:
4449
end = i + 1;
50+
4551
break;
4652
}
4753
}
4854

49-
return !compareETags(etag, noneMatch.substring(start, end));
55+
return !compareETags(etag, noneMatch.slice(start, end));
5056
}
5157

5258
/**
@@ -81,10 +87,7 @@ export default function fresh(
8187
if (modifiedSince) {
8288
const lastModified = resHeaders["last-modified"] as string | undefined;
8389

84-
if (
85-
!lastModified
86-
|| !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince))
87-
) return false;
90+
if (!lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince))) return false;
8891
}
8992

9093
return true;

0 commit comments

Comments
 (0)