bb-inspired
Version:
Core library for BB-inspired NestJS backend
146 lines • 5.52 kB
JavaScript
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var MemoryCacheService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MemoryCacheService = void 0;
const common_1 = require("@nestjs/common");
const logger_1 = require("../../utils/logger");
let MemoryCacheService = MemoryCacheService_1 = class MemoryCacheService {
constructor(options) {
var _a, _b;
this.options = options;
this.logger = new logger_1.AppLogger(MemoryCacheService_1.name);
this.cache = new Map();
this.tagMap = new Map();
this.defaultTtl = ((_a = options.memory) === null || _a === void 0 ? void 0 : _a.ttl) || 3600;
this.maxItems = ((_b = options.memory) === null || _b === void 0 ? void 0 : _b.max) || 1000;
this.logger.log(`Memory cache initialized with ${this.maxItems} max items`);
setInterval(() => this.cleanup(), 60000);
}
async get(key) {
const entry = this.cache.get(key);
if (!entry) {
return null;
}
if (entry.expiresAt && entry.expiresAt < Date.now()) {
await this.delete(key);
return null;
}
return entry.value;
}
async set(key, value, options = {}) {
var _a;
const ttl = (_a = options.ttl) !== null && _a !== void 0 ? _a : this.defaultTtl;
const entry = {
value,
expiresAt: ttl > 0 ? Date.now() + ttl * 1000 : undefined,
tags: options.tags,
};
if (this.cache.size >= this.maxItems && !this.cache.has(key)) {
this.evictOldest();
}
this.cache.set(key, entry);
if (options.tags && options.tags.length > 0) {
for (const tag of options.tags) {
if (!this.tagMap.has(tag)) {
this.tagMap.set(tag, new Set());
}
this.tagMap.get(tag).add(key);
}
}
}
async delete(key) {
const entry = this.cache.get(key);
if (!entry) {
return false;
}
if (entry.tags && entry.tags.length > 0) {
for (const tag of entry.tags) {
const tagSet = this.tagMap.get(tag);
if (tagSet) {
tagSet.delete(key);
if (tagSet.size === 0) {
this.tagMap.delete(tag);
}
}
}
}
return this.cache.delete(key);
}
async clear() {
this.cache.clear();
this.tagMap.clear();
this.logger.log('Cleared all cache entries');
}
async has(key) {
const entry = this.cache.get(key);
if (!entry) {
return false;
}
if (entry.expiresAt && entry.expiresAt < Date.now()) {
await this.delete(key);
return false;
}
return true;
}
async invalidateByTag(tag) {
const tagSet = this.tagMap.get(tag);
if (!tagSet || tagSet.size === 0) {
return;
}
const keysToDelete = Array.from(tagSet);
for (const key of keysToDelete) {
await this.delete(key);
}
this.tagMap.delete(tag);
this.logger.log(`Invalidated ${keysToDelete.length} cache entries with tag ${tag}`);
}
cleanup() {
const now = Date.now();
let expiredCount = 0;
for (const [key, entry] of this.cache.entries()) {
if (entry.expiresAt && entry.expiresAt < now) {
this.delete(key);
expiredCount++;
}
}
if (expiredCount > 0) {
this.logger.verbose(`Cleaned up ${expiredCount} expired cache entries`);
}
}
evictOldest() {
let oldestKey = null;
let oldestTime = Infinity;
for (const [key, entry] of this.cache.entries()) {
if (entry.expiresAt && entry.expiresAt < oldestTime) {
oldestTime = entry.expiresAt;
oldestKey = key;
}
}
if (!oldestKey) {
oldestKey = this.cache.keys().next().value;
}
if (oldestKey) {
this.delete(oldestKey);
this.logger.verbose(`Evicted oldest cache entry: ${oldestKey}`);
}
}
};
exports.MemoryCacheService = MemoryCacheService;
exports.MemoryCacheService = MemoryCacheService = MemoryCacheService_1 = __decorate([
(0, common_1.Injectable)(),
__param(0, (0, common_1.Inject)('CACHE_OPTIONS')),
__metadata("design:paramtypes", [Object])
], MemoryCacheService);
//# sourceMappingURL=memory-cache.service.js.map