cachly
Version:
Type-safe, production-ready in-memory cache system for Node.js and TypeScript with advanced features.
67 lines • 3.02 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.invalidateTags = exports.cacheWithTags = exports.cacheMethod = exports.invalidate = exports.cache = exports.CacheDecorators = void 0;
const Cachly_1 = require("./Cachly");
class CacheDecorators {
static setDefaultCache(cache) {
CacheDecorators.defaultCache = cache;
}
static cache(options = {}) {
return function (target, propertyKey, descriptor) {
const originalMethod = descriptor.value;
descriptor.value = async function (...args) {
const cacheKey = typeof options.key === 'function'
? options.key(args)
: options.key || `${target.constructor.name}:${propertyKey}:${JSON.stringify(args)}`;
const cacheOptions = {
...(options.ttl !== undefined && { ttl: options.ttl }),
...(options.tags !== undefined && { tags: options.tags }),
...(options.dependsOn !== undefined && { dependsOn: options.dependsOn }),
};
return await CacheDecorators.defaultCache.getOrCompute(cacheKey, () => originalMethod.apply(this, args), cacheOptions);
};
return descriptor;
};
}
static invalidate(options) {
return function (_target, _propertyKey, descriptor) {
const originalMethod = descriptor.value;
descriptor.value = async function (...args) {
const result = await originalMethod.apply(this, args);
if (options.tags) {
await CacheDecorators.defaultCache.invalidateByTags(options.tags);
}
if (options.keys) {
for (const key of options.keys) {
CacheDecorators.defaultCache.delete(key);
}
}
if (options.pattern) {
const keys = CacheDecorators.defaultCache.getKeysByPattern(options.pattern);
for (const key of keys) {
CacheDecorators.defaultCache.delete(key);
}
}
return result;
};
return descriptor;
};
}
static cacheMethod(key, ttl) {
return CacheDecorators.cache({ key, ...(ttl !== undefined && { ttl }) });
}
static cacheWithTags(tags, ttl) {
return CacheDecorators.cache({ tags, ...(ttl !== undefined && { ttl }) });
}
static invalidateTags(tags) {
return CacheDecorators.invalidate({ tags });
}
}
exports.CacheDecorators = CacheDecorators;
CacheDecorators.defaultCache = new Cachly_1.Cachly();
exports.cache = CacheDecorators.cache;
exports.invalidate = CacheDecorators.invalidate;
exports.cacheMethod = CacheDecorators.cacheMethod;
exports.cacheWithTags = CacheDecorators.cacheWithTags;
exports.invalidateTags = CacheDecorators.invalidateTags;
//# sourceMappingURL=decorators.js.map