five-server
Version:
Development Server with Live Reload Capability. (Maintained Fork of Live Server)
48 lines • 1.91 kB
JavaScript
;
/**
* @author Yannick Deubel (https://github.com/yandeu)
* @copyright Copyright (c) 2021 Yannick Deubel
* @license {@link https://github.com/yandeu/five-server/blob/main/LICENSE LICENSE}
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.cache = void 0;
const path_1 = require("path");
const fileTypes_1 = require("../fileTypes");
const nodeFetch_1 = require("../nodeFetch");
const _cache = new Map();
const _maxCacheTime = 3600; // one hour (in seconds)
const cache = async (req, res, next) => {
var _a;
let url = (_a = req.url) === null || _a === void 0 ? void 0 : _a.replace(/^\//, '');
const protocol = req.protocol;
const host = req.headers['host'];
const method = req.method;
const ext = (0, path_1.extname)(new URL(url, 'http://localhost:8080').pathname);
const now = new Date().getTime();
const id = `${method}_${url}`;
const data = _cache.get(id);
if (data) {
const age = Math.round((now - (data === null || data === void 0 ? void 0 : data.timestamp)) / 1000);
if (age < _maxCacheTime) {
res.setHeader('Age', age);
res.setHeader('X-Cache', 'Hit from fiveserver');
return res.type(ext).send(data.file);
}
}
try {
// if the url is a relative path, prepend protocol and host
if (!/^https?:\/\//.test(url))
url = `${protocol}://${host}/${url}`;
const data = await (0, nodeFetch_1.nodeFetch)(url);
const file = fileTypes_1.fileTypes.isImage(ext) ? data : data.toString('utf-8');
_cache.set(id, { timestamp: now, file });
res.setHeader('Age', 0);
res.setHeader('X-Cache', 'Miss from fiveserver');
return res.type(ext).send(file);
}
catch (error) {
return res.status(error.code).send(error.message);
}
};
exports.cache = cache;
//# sourceMappingURL=cache.js.map