hypershield
Version:
Middleware suite for high-performance and resilient APIs
47 lines • 2.15 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.cacheMiddleware = void 0;
const constants_1 = require("../../../core/constants/constants");
const cacheMiddleware = (cacheManager, options = {}) => {
return (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
if (req.method !== 'GET') {
return next();
}
const cacheKey = generateCacheKey(req, options);
try {
const cachedResponse = yield cacheManager.get(cacheKey);
if (cachedResponse) {
res.json(cachedResponse);
return;
}
const originalJson = res.json;
res.json = function (body) {
cacheManager.set(cacheKey, body, options.ttl || constants_1.CACHE.DEFAULT_TTL)
.catch(err => console.error('Cache set error:', err));
return originalJson.call(this, body);
};
next();
}
catch (error) {
console.error('Cache middleware error:', error);
next();
}
});
};
exports.cacheMiddleware = cacheMiddleware;
function generateCacheKey(req, options) {
const prefix = options.keyPrefix || 'cache';
const path = req.path;
const query = options.ignoreQueryParams ? '' : JSON.stringify(req.query);
return `${prefix}:${path}${query ? `:${query}` : ''}`;
}
//# sourceMappingURL=cacheMiddleware.js.map