cachly
Version:
Type-safe, production-ready in-memory cache system for Node.js and TypeScript with advanced features.
80 lines • 3.11 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.invalidateMiddleware = exports.cacheMiddleware = void 0;
exports.createCacheMiddleware = createCacheMiddleware;
exports.createInvalidateMiddleware = createInvalidateMiddleware;
function createCacheMiddleware(options) {
const { cache, keyGenerator = (req) => `${req.method}:${req.originalUrl}`, ttl, tags, dependsOn, skip = () => false, statusCodes = [200], } = options;
return async (req, res, next) => {
if (skip(req)) {
return next();
}
const key = keyGenerator(req);
const cacheOptions = {
...(ttl !== undefined && { ttl }),
...(tags !== undefined && { tags: typeof tags === 'function' ? tags(req) : tags }),
...(dependsOn !== undefined && { dependsOn: typeof dependsOn === 'function' ? dependsOn(req) : dependsOn }),
};
try {
const cachedResponse = await cache.get(key);
if (cachedResponse) {
return res.json(cachedResponse);
}
// Store original send method
const originalSend = res.send;
const originalJson = res.json;
// Override send method to cache responses
res.send = function (body) {
if (statusCodes.includes(res.statusCode)) {
cache.set(key, body, cacheOptions);
}
return originalSend.call(this, body);
};
res.json = function (body) {
if (statusCodes.includes(res.statusCode)) {
cache.set(key, body, cacheOptions);
}
return originalJson.call(this, body);
};
next();
}
catch (error) {
next(error);
}
};
}
function createInvalidateMiddleware(options) {
const { cache, tags, keys, pattern } = options;
return async (req, _, next) => {
try {
// Invalidate by tags
if (tags) {
const tagsToInvalidate = typeof tags === 'function' ? tags(req) : tags;
await cache.invalidateByTags(tagsToInvalidate);
}
// Invalidate by keys
if (keys) {
const keysToInvalidate = typeof keys === 'function' ? keys(req) : keys;
for (const key of keysToInvalidate) {
cache.delete(key);
}
}
// Invalidate by pattern
if (pattern) {
const patternToUse = typeof pattern === 'function' ? pattern(req) : pattern;
const keysToDelete = cache.getKeysByPattern(patternToUse);
for (const key of keysToDelete) {
cache.delete(key);
}
}
next();
}
catch (error) {
next(error);
}
};
}
// Convenience functions
exports.cacheMiddleware = createCacheMiddleware;
exports.invalidateMiddleware = createInvalidateMiddleware;
//# sourceMappingURL=express.js.map