/* * @author gs * @date 2020/11/26 13:50 */ import { RedisClient } from '../common/cache/redis.client'; export abstract class CacheBaseService { expirationTime = 3600; // seconds abstract async getFromDatabase(dataId?: string): Promise; abstract set cacheKey(key: string); public async getData(dataId?: string): Promise { let value = await this.getFromCache(this.getCacheKey(dataId)); if (!value) { value = await this.getFromDatabase(dataId); } if (!value) { return undefined; } this.setToCache(value, dataId).then(); return value as T; } public async setToCache(data: T, dataId?: string): Promise { await RedisClient.getInstance().setExpire({ key: this.getCacheKey(dataId), value: JSON.stringify(data), time: this.expirationTime }); } private async getFromCache(cacheKey: string): Promise { const value = await RedisClient.getInstance().get(cacheKey); return value ? (JSON.parse(value) as T) : undefined; } private getCacheKey(dataId?: string): string { return dataId ? `${this.cacheKey}${dataId}` : this.cacheKey; } }