import {
CacheInterface,
CacheReturnType
} from '../../interfaces/cache.interface';
import { StatusEnum } from '../../interfaces/generic.interface';
// import getUserId from '../default/userId';
import RedisHelper from './RedisHelper';
function getUserId () {
return Math.random(); // 在这里使用您的逻辑!
}
export default class CacheHelper {
// 检查缓存是否为空
// 然后运行回调函数
// 并用结果设置缓存
static async checkCache({
key,
callback,
configs
}: CacheInterface): CacheReturnType {
const cache = await RedisHelper.get(key);
const expirationInSeconds = configs?.expirationInSeconds || 3600;
// 仅在configs中指定时才在键中使用userId
if (configs?.useUserId) {
const userId = getUserId();
key = `${key}:${userId}`;
}
if (cache) {
return {
status: StatusEnum.SUCCESS,
data: cache
};
}
try {
const result = await callback();
if (result.status === StatusEnum.ERROR) {
return {
status: StatusEnum.ERROR,
data: result.data
};
}
await RedisHelper.set(key, result.data, expirationInSeconds);
return {
status: StatusEnum.SUCCESS,
data: result.data
};
} catch (error) {
console.error('Error in checkCache:', error);
return {
status: StatusEnum.ERROR,
data: null
};
}
}
// 辅助函数,始终在键中使用userId
static async checkCacheWithId({
key,
callback,
configs
}: CacheInterface): CacheReturnType {
return this.checkCache({
key,
callback,
configs: {
...configs,
useUserId: true
}
});
}
static async deleteCache(
key: string,
configs?: {
useUserId?: boolean;
}
): Promise<void> {
if (configs?.useUserId) {
const userId = getUserId();
key = `${key}:${userId}`;
}
if (!key) {
throw new Error('Key is required to delete cache');
}
try {
await RedisHelper.del(key);
} catch (error) {
console.error('Error deleting cache:', error);
throw error;
}
}
static async deleteUserCache(key: string): Promise<void> {
return this.deleteCache(key, { useUserId: true });
}
}