@amirmarmul/waba-common
Version:

102 lines (101 loc) • 3.2 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Cache = void 0;
const ioredis_1 = require("ioredis");
const Repo_1 = require("../../../core/infrastructure/cache/Repo");
const NullStore_1 = require("../../../core/infrastructure/cache/stores/NullStore");
const ArrayStore_1 = require("../../../core/infrastructure/cache/stores/ArrayStore");
const RedisStore_1 = require("../../../core/infrastructure/cache/stores/RedisStore");
const FileStore_1 = require("../../../core/infrastructure/cache/stores/FileStore");
class Cache {
stores = {};
config;
constructor(config) {
this.config = config;
}
driver(driver) {
return this.store(driver);
}
store(name) {
name = name || this.getDefaultDriver();
if (!(name in this.stores)) {
this.stores[name] = this.resolve(name);
}
return this.stores[name];
}
resolve(name) {
const config = this.getConfig(name);
if (!config) {
throw new Error(`Cache store [${name}] is not defined.`);
}
const driverMethod = config.driver + 'Driver';
if (this[driverMethod]) {
return this[driverMethod](config);
}
throw new Error(`Cache driver [${config.driver}] is not supported.`);
}
getConfig(name) {
if (name && name !== 'null') {
return this.config.stores[name];
}
return { driver: 'null' };
}
getPrefix() {
return this.config.prefix;
}
getDefaultDriver() {
return this.config.store;
}
nullDriver(config) {
return new Repo_1.Repo(new NullStore_1.NullStore());
}
arrayDriver(config) {
return new Repo_1.Repo(new ArrayStore_1.ArrayStore());
}
fileDriver(config) {
const path = config.path || 'storage/cache/data';
return new Repo_1.Repo(new FileStore_1.FileStore(path));
}
redisDriver(config) {
const redis = new ioredis_1.Redis(config.redisUrl);
const prefix = this.getPrefix();
return new Repo_1.Repo(new RedisStore_1.RedisStore(redis, prefix));
}
/**
* CacheContract
*/
async has(key) {
return await this.store().has(key);
}
async missing(key) {
return await this.store().missing(key);
}
async get(key, _default) {
return await this.store().get(key, _default);
}
async pull(key, _default) {
return await this.store().pull(key, _default);
}
async put(key, value, ttl) {
return await this.store().put(key, value, ttl);
}
async add(key, value, ttl) {
return await this.store().add(key, value, ttl);
}
async forever(key, value) {
return await this.store().forever(key, value);
}
async remember(key, callback, ttl) {
return await this.store().remember(key, callback, ttl);
}
async rememberForever(key, callback) {
return await this.store().rememberForever(key, callback);
}
async forget(key) {
return await this.store().forget(key);
}
async flush() {
return await this.store().flush();
}
}
exports.Cache = Cache;