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