2025-05-28 09:27:12 -04:00
|
|
|
const path = require('path');
|
2025-02-22 23:42:20 +01:00
|
|
|
const expressStaticGzip = require('express-static-gzip');
|
2024-08-04 21:17:59 -04:00
|
|
|
|
2024-08-26 15:34:46 -04:00
|
|
|
const oneDayInSeconds = 24 * 60 * 60;
|
2024-08-04 21:17:59 -04:00
|
|
|
|
2024-08-26 15:34:46 -04:00
|
|
|
const sMaxAge = process.env.STATIC_CACHE_S_MAX_AGE || oneDayInSeconds;
|
|
|
|
|
const maxAge = process.env.STATIC_CACHE_MAX_AGE || oneDayInSeconds * 2;
|
2024-08-04 21:17:59 -04:00
|
|
|
|
2025-05-28 09:27:12 -04:00
|
|
|
/**
|
|
|
|
|
* Creates an Express static middleware with gzip compression and configurable caching
|
|
|
|
|
*
|
|
|
|
|
* @param {string} staticPath - The file system path to serve static files from
|
|
|
|
|
* @param {Object} [options={}] - Configuration options
|
|
|
|
|
* @param {boolean} [options.noCache=false] - If true, disables caching entirely for all files
|
|
|
|
|
* @returns {ReturnType<expressStaticGzip>} Express middleware function for serving static files
|
|
|
|
|
*/
|
|
|
|
|
function staticCache(staticPath, options = {}) {
|
|
|
|
|
const { noCache = false } = options;
|
|
|
|
|
return expressStaticGzip(staticPath, {
|
|
|
|
|
enableBrotli: false,
|
2025-02-22 23:42:20 +01:00
|
|
|
orderPreference: ['gz'],
|
2025-05-28 09:27:12 -04:00
|
|
|
setHeaders: (res, filePath) => {
|
|
|
|
|
if (process.env.NODE_ENV?.toLowerCase() !== 'production') {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
if (noCache) {
|
|
|
|
|
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate');
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
if (filePath.includes('/dist/images/')) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
const fileName = path.basename(filePath);
|
|
|
|
|
|
|
|
|
|
if (
|
|
|
|
|
fileName === 'index.html' ||
|
|
|
|
|
fileName.endsWith('.webmanifest') ||
|
|
|
|
|
fileName === 'manifest.json' ||
|
|
|
|
|
fileName === 'sw.js'
|
|
|
|
|
) {
|
|
|
|
|
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate');
|
|
|
|
|
} else {
|
2025-02-22 23:42:20 +01:00
|
|
|
res.setHeader('Cache-Control', `public, max-age=${maxAge}, s-maxage=${sMaxAge}`);
|
2024-08-04 21:17:59 -04:00
|
|
|
}
|
|
|
|
|
},
|
2025-05-16 23:18:52 +09:00
|
|
|
index: false,
|
2024-08-04 21:17:59 -04:00
|
|
|
});
|
2025-05-28 09:27:12 -04:00
|
|
|
}
|
2024-08-04 21:17:59 -04:00
|
|
|
|
|
|
|
|
module.exports = staticCache;
|