66 lines
2.5 KiB
JavaScript
66 lines
2.5 KiB
JavaScript
|
"use strict";
|
||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||
|
};
|
||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||
|
exports.MAX_SIZE_FOR_NON_PROCESSED_RESOURCE = exports.getResponse = exports.add = exports.create = exports.shouldCache = void 0;
|
||
|
const lru_cache_1 = __importDefault(require("lru-cache"));
|
||
|
const http_cache_semantics_1 = __importDefault(require("http-cache-semantics"));
|
||
|
const incoming_message_like_1 = __importDefault(require("./incoming-message-like"));
|
||
|
const requestsCache = new lru_cache_1.default({
|
||
|
max: 50 * 1024 * 1024,
|
||
|
length: responseCacheEntry => {
|
||
|
var _a;
|
||
|
// NOTE: Length is resource content size.
|
||
|
// 1 character is 1 bite.
|
||
|
return ((_a = responseCacheEntry.res.getBody()) === null || _a === void 0 ? void 0 : _a.length) || 0;
|
||
|
},
|
||
|
});
|
||
|
function getCacheKey(requestOptions) {
|
||
|
// NOTE: We don't use pair <method:url> as a cache key since we cache only GET requests
|
||
|
return requestOptions.url;
|
||
|
}
|
||
|
// NOTE: export for testing purposes
|
||
|
function shouldCache(ctx) {
|
||
|
return ctx.serverInfo.cacheRequests && !ctx.isFileProtocol && ctx.reqOpts.method === 'GET' &&
|
||
|
(ctx.contentInfo.isCSS || ctx.contentInfo.isScript || !ctx.contentInfo.requireProcessing);
|
||
|
}
|
||
|
exports.shouldCache = shouldCache;
|
||
|
function create(reqOptions, res) {
|
||
|
const cachePolicy = new http_cache_semantics_1.default(reqOptions, res);
|
||
|
if (!cachePolicy.storable())
|
||
|
return void 0;
|
||
|
return {
|
||
|
key: getCacheKey(reqOptions),
|
||
|
value: {
|
||
|
cachePolicy,
|
||
|
res: incoming_message_like_1.default.createFrom(res),
|
||
|
hitCount: 0,
|
||
|
},
|
||
|
};
|
||
|
}
|
||
|
exports.create = create;
|
||
|
function add(entry) {
|
||
|
const { key, value } = entry;
|
||
|
requestsCache.set(key, value, value.cachePolicy.timeToLive());
|
||
|
}
|
||
|
exports.add = add;
|
||
|
function getResponse(reqOptions) {
|
||
|
const key = getCacheKey(reqOptions);
|
||
|
const cachedResponse = requestsCache.get(key);
|
||
|
if (!cachedResponse)
|
||
|
return void 0;
|
||
|
const { cachePolicy, res } = cachedResponse;
|
||
|
if (!cachePolicy.satisfiesWithoutRevalidation(reqOptions))
|
||
|
return void 0;
|
||
|
res.headers = cachePolicy.responseHeaders();
|
||
|
cachedResponse.hitCount++;
|
||
|
return {
|
||
|
res,
|
||
|
hitCount: cachedResponse.hitCount,
|
||
|
};
|
||
|
}
|
||
|
exports.getResponse = getResponse;
|
||
|
// NOTE: Maximum size for the non processed resource is 5 Mb
|
||
|
exports.MAX_SIZE_FOR_NON_PROCESSED_RESOURCE = 5 * 1024 * 1024;
|