2015-05-18 21:12:42 +03:00
|
|
|
// # CacheControl Middleware
|
|
|
|
// Usage: cacheControl(profile), where profile is one of 'public' or 'private'
|
|
|
|
// After: checkIsPrivate
|
|
|
|
// Before: routes
|
2017-10-26 19:24:08 +03:00
|
|
|
// App: Admin|Site|API
|
2015-05-18 21:12:42 +03:00
|
|
|
//
|
|
|
|
// Allows each app to declare its own default caching rules
|
|
|
|
|
2018-09-20 16:03:33 +03:00
|
|
|
const isString = require('lodash/isString');
|
2015-05-18 21:12:42 +03:00
|
|
|
|
2022-01-14 14:34:35 +03:00
|
|
|
/**
|
|
|
|
* @param {'public'|'private'} profile Use "private" if you do not want caching
|
|
|
|
* @param {object} [options]
|
|
|
|
* @param {number} [options.maxAge] The max-age in seconds to use when profile is "public"
|
2022-11-02 08:57:23 +03:00
|
|
|
* @param {number} [options.staleWhileRevalidate] The stale-while-revalidate in seconds to use when profile is "public"
|
2022-01-14 14:34:35 +03:00
|
|
|
*/
|
2020-04-22 19:27:43 +03:00
|
|
|
const cacheControl = (profile, options = {maxAge: 0}) => {
|
2022-11-02 08:57:23 +03:00
|
|
|
const isOptionHasProperty = property => Object.prototype.hasOwnProperty.call(options, property);
|
|
|
|
const publicOptions = [
|
|
|
|
'public',
|
|
|
|
`max-age=${options.maxAge}`,
|
|
|
|
isOptionHasProperty('staleWhileRevalidate') ? `stale-while-revalidate=${options.staleWhileRevalidate}` : ''
|
|
|
|
];
|
|
|
|
|
2018-09-10 15:07:57 +03:00
|
|
|
const profiles = {
|
2022-11-02 08:57:23 +03:00
|
|
|
public: publicOptions.filter(option => option).join(', '),
|
2018-09-10 15:07:57 +03:00
|
|
|
private: 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0'
|
|
|
|
};
|
|
|
|
|
|
|
|
let output;
|
2015-05-18 21:12:42 +03:00
|
|
|
|
2020-04-22 19:27:43 +03:00
|
|
|
if (isString(profile) && Object.prototype.hasOwnProperty.call(profiles, profile)) {
|
|
|
|
output = profiles[profile];
|
2015-05-18 21:12:42 +03:00
|
|
|
}
|
|
|
|
|
2022-01-14 14:34:35 +03:00
|
|
|
/**
|
|
|
|
* @param {import('express').Request} req
|
|
|
|
* @param {import('express').Response} res
|
|
|
|
* @param {() => void} next
|
|
|
|
*
|
|
|
|
* @returns {void}
|
|
|
|
*/
|
2015-05-18 21:12:42 +03:00
|
|
|
return function cacheControlHeaders(req, res, next) {
|
|
|
|
if (output) {
|
2020-04-22 19:27:43 +03:00
|
|
|
res.set({'Cache-Control': output});
|
2015-05-18 21:12:42 +03:00
|
|
|
}
|
|
|
|
next();
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = cacheControl;
|