@anthro.id/express-cache-control
Version:
Apply a cache control header through Express middleware.
82 lines (81 loc) • 2.96 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = default_1;
const on_headers_1 = __importDefault(require("on-headers"));
const isNumber = (input) => typeof input === "number" || !isNaN(+input);
function default_1(options = {}) {
return function (req, res, next) {
res.cacheControl = options;
(0, on_headers_1.default)(res, function () {
var _a;
let options = (this === null || this === void 0 ? void 0 : this.cacheControl) || {};
let cacheControl = [];
if (options.private) {
cacheControl.push('private');
}
else if (options.public) {
cacheControl.push('public');
}
;
if (options.immutable) {
cacheControl.push("immutable");
}
;
if (options.noStore) {
options.noCache = true;
cacheControl.push('no-store');
}
;
if (options.noCache) {
options.maxAge = 0;
delete options.sMaxAge;
cacheControl.push('no-cache');
}
;
if (options.noTransform) {
cacheControl.push('no-transform');
}
;
if (options.proxyRevalidate) {
cacheControl.push('proxy-revalidate');
}
;
if (options.mustUnderstand) {
cacheControl.push("must-understand");
}
;
if (options.mustRevalidate) {
cacheControl.push('must-revalidate');
}
else if (!options.noCache) {
if (options.staleIfError) {
cacheControl.push('stale-if-error=' + options.staleIfError);
}
;
if (options.staleWhileRevalidate) {
cacheControl.push('stale-while-revalidate=' + options.staleWhileRevalidate);
}
;
}
;
if (isNumber(options.maxAge)) {
cacheControl.push("max-age=" + options.maxAge);
}
;
if (isNumber(options.sMaxAge)) {
cacheControl.push("s-maxage=" + options.sMaxAge);
}
;
const isPreappliedHeadersPresented = typeof res !== "undefined" && "hasHeader" in res && ((_a = res === null || res === void 0 ? void 0 : res.hasHeader) === null || _a === void 0 ? void 0 : _a.call(res, "Cache-Control"));
if (cacheControl.length && !isPreappliedHeadersPresented) {
this.setHeader('Cache-Control', cacheControl.join(','));
}
;
});
next();
};
}
;