@ticatec/redis-client
Version:
A lightweight TypeScript wrapper around ioredis with singleton pattern support, mock Redis for testing, and abstract caching framework.
56 lines • 1.78 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const RedisClient_1 = __importDefault(require("../RedisClient"));
/**
* 抽象缓存数据基类
* 提供通用的缓存数据操作方法,子类需要实现具体的数据处理逻辑
* @abstract
* @template T - 缓存键的类型
*/
class AbstractCachedData {
/**
* 构造函数
* @protected
* @param {GetKey<T>} getKey - 根据缓存键生成Redis键名的函数
* @param {number} [ttl=0] - 缓存过期时间(秒),0表示永不过期
*/
constructor(getKey, ttl = 0) {
/**
* Redis客户端实例
* @protected
* @type {RedisClient}
*/
this.redisClient = RedisClient_1.default.getInstance();
this.getKey = getKey;
this.ttl = ttl;
}
/**
* 从缓存加载数据
* @param {Partial<T>} key - 缓存键(可以是部分对象)
* @returns {Promise<T>} 缓存的数据对象
*/
async load(key) {
return await this.redisClient.getObject(this.getKey(key));
}
/**
* 清除指定键的缓存数据
* @param {Partial<T>} key - 缓存键(可以是部分对象)
* @returns {Promise<void>}
*/
async clean(key) {
await this.redisClient.del(this.getKey(key));
}
/**
* 保存数据到缓存
* @param {T} data - 要保存的完整数据对象
* @returns {Promise<void>}
*/
async save(data) {
await this.redisClient.set(this.getKey(data), data, this.ttl);
}
}
exports.default = AbstractCachedData;
//# sourceMappingURL=AbstractCachedData.js.map