hypershield
Version:
Middleware suite for high-performance and resilient APIs
67 lines • 2.83 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.CacheManager = void 0;
const constants_1 = require("../../core/constants/constants");
const memory_1 = require("../../shared/cache/memory");
const redis_1 = require("../../shared/cache/redis");
class CacheManager {
constructor(config) {
this.config = config;
}
initialize() {
this.provider = this.createProvider();
}
createProvider() {
var _a, _b;
switch (this.config.provider) {
case 'redis':
if (!((_a = this.config.connection) === null || _a === void 0 ? void 0 : _a.host)) {
throw new Error('Redis host is required');
}
return new redis_1.RedisCache({
host: this.config.connection.host,
port: (_b = this.config.connection.port) !== null && _b !== void 0 ? _b : 6379,
password: this.config.connection.password
});
case 'memory':
return new memory_1.MemoryCache();
default:
throw new Error(`Unsupported cache provider: ${this.config.provider}`);
}
}
ensureInitialized() {
if (!this.provider) {
throw new Error('Cache manager not initialized. Call initialize() first.');
}
}
get(key) {
return __awaiter(this, void 0, void 0, function* () {
this.ensureInitialized();
return this.provider.get(key);
});
}
set(key, value, ttl) {
return __awaiter(this, void 0, void 0, function* () {
this.ensureInitialized();
const validTtl = Math.min(Math.max(ttl || constants_1.CACHE.DEFAULT_TTL, constants_1.CACHE.MIN_TTL), constants_1.CACHE.MAX_TTL);
yield this.provider.set(key, value, validTtl);
});
}
delete(key) {
return __awaiter(this, void 0, void 0, function* () {
this.ensureInitialized();
yield this.provider.delete(key);
});
}
}
exports.CacheManager = CacheManager;
//# sourceMappingURL=cacheManager.js.map