refactor: move cache headers logic into reusable functions (#4533)

* refactor: move cache headers logic into reusable functions

* dev

---------

Co-authored-by: Alexandr <qwerty541zxc@gmail.com>
This commit is contained in:
Alexandr Garbuzov
2025-10-07 00:13:21 +03:00
committed by GitHub
co-authored by Alexandr
parent ade7d53653
commit 09627ce715
10 changed files with 100 additions and 94 deletions
+33 -3
View File
@@ -1,4 +1,6 @@
import { clampValue } from "./utils";
// @ts-check
import { clampValue, CONSTANTS } from "./utils.js";
/**
* Resolves the cache seconds based on the requested, default, min, and max values.
@@ -11,7 +13,7 @@ import { clampValue } from "./utils";
* @returns {number} The resolved cache seconds.
*/
const resolveCacheSeconds = ({ requested, def, min, max }) => {
let cacheSeconds = clampValue(parseInt(requested || def, 10), min, max);
let cacheSeconds = clampValue(isNaN(requested) ? def : requested, min, max);
cacheSeconds = process.env.CACHE_SECONDS
? parseInt(process.env.CACHE_SECONDS, 10) || cacheSeconds
@@ -20,4 +22,32 @@ const resolveCacheSeconds = ({ requested, def, min, max }) => {
return cacheSeconds;
};
export { resolveCacheSeconds };
/**
* Sets the Cache-Control headers on the response object.
*
* @param {Object} res The response object.
* @param {number} cacheSeconds The cache seconds to set in the headers.
*/
const setCacheHeaders = (res, cacheSeconds) => {
res.setHeader(
"Cache-Control",
`max-age=${cacheSeconds}, s-maxage=${cacheSeconds}, stale-while-revalidate=${CONSTANTS.ONE_DAY}`,
);
};
/**
* Sets the Cache-Control headers for error responses on the response object.
*
* @param {Object} res The response object.
*/
const setErrorCacheHeaders = (res) => {
// Use lower cache period for errors.
res.setHeader(
"Cache-Control",
`max-age=${CONSTANTS.ERROR_CACHE_SECONDS}, ` +
`s-maxage=${CONSTANTS.ERROR_CACHE_SECONDS}, ` +
`stale-while-revalidate=${CONSTANTS.ONE_DAY}`,
);
};
export { resolveCacheSeconds, setCacheHeaders, setErrorCacheHeaders };