From 5b5f7bb0e7eb8d4e30f016069b3eb32368c996fc Mon Sep 17 00:00:00 2001 From: Dorian Niemiec Date: Sun, 15 Dec 2024 20:47:38 +0100 Subject: [PATCH] feat: add support for "s-maxage" directive in "Cache-Control" header --- src/utils/cacheControlUtils.js | 10 ++++++++-- tests/utils/cacheControlUtils.test.js | 10 ++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/utils/cacheControlUtils.js b/src/utils/cacheControlUtils.js index e652259..a593f86 100644 --- a/src/utils/cacheControlUtils.js +++ b/src/utils/cacheControlUtils.js @@ -20,12 +20,18 @@ function shouldCacheResponse(cacheControl, isAuthenticated) { if (cacheControl["public"]) { return true; } - return !isAuthenticated && cacheControl["max-age"] !== undefined; + return ( + !isAuthenticated && + (cacheControl["max-age"] !== undefined || + cacheControl["s-maxage"] !== undefined) + ); } function isCacheValid(entry, requestHeaders) { const { timestamp, cacheControl } = entry; - const maxAge = parseInt(cacheControl["max-age"], 10); + const maxAge = cacheControl["s-maxage"] + ? parseInt(cacheControl["s-maxage"], 10) + : parseInt(cacheControl["max-age"], 10); if (Date.now() - timestamp > maxAge * 1000) { return false; } diff --git a/tests/utils/cacheControlUtils.test.js b/tests/utils/cacheControlUtils.test.js index 234d286..8cfa15a 100644 --- a/tests/utils/cacheControlUtils.test.js +++ b/tests/utils/cacheControlUtils.test.js @@ -81,6 +81,16 @@ describe("shouldCacheResponse", () => { expect(shouldCacheResponse(cacheControl, true)).toBe(false); }); + test("should return true if s-maxage is present and not authenticated", () => { + const cacheControl = { "s-maxage": "3600" }; + expect(shouldCacheResponse(cacheControl, false)).toBe(true); + }); + + test("should return false if s-maxage is present and authenticated", () => { + const cacheControl = { "s-maxage": "3600" }; + expect(shouldCacheResponse(cacheControl, true)).toBe(false); + }); + test("should return false if no relevant directives are present", () => { const cacheControl = {}; expect(shouldCacheResponse(cacheControl, false)).toBe(false);