typescript - 有没有办法取消猫鼬查找执行并从redis返回数据?
问题描述
我正在尝试在nest.js中与mongoose一起实现Redis缓存,我正在寻找一种在执行find或findOne之前先检查redis缓存并从redis返回数据的方法,否则执行查询,将结果保存在redis中并返回结果。我没有像nest.js 推荐的那样实现缓存的原因是我也在使用Apollo Server for GraphQL。
@Injectable()
export class MyService {
async getItem(where): Promise<ItemModel> {
const fromCache = await this.cacheService.getValue('itemId');
if(!!fromCache){
return JSON.parse(fromCache);
} else {
const response = await this.ItemModel.find(where);
this.cacheService.setValue('itemId', JSON.stringify(response));
return response
}
}
}
我想将这段代码移动到一个地方,这样我就不必为代码中的每个查询重复此代码,因为我有多个服务。我知道 mongoose 中间件有一种方法可以在查询中运行 pre 和 post 函数,但我只是不确定如何使用它来完成此操作。
这些是我正在使用的版本:
- 巢穴 v7
- 猫鼬 v5.10.0
解决方案
您可以创建一个方法装饰器,将逻辑移至:
export const UseCache = (cacheKey:string) => (_target: any, _field: string, descriptor: TypedPropertyDescriptor<any>) => {
const originalMethod = descriptor.value;
// note: important to use non-arrow function here to preserve this-context
descriptor.value = async function(...args: any[]) {
const fromCache = await this.cacheService.getValue(cacheKey);
if(!!fromCache){
return JSON.parse(fromCache);
}
const result = await originalMethod.apply(this, args);
await this.cacheService.setValue(cacheKey, JSON.stringify(result));
return result;
};
}
然后将其用于:
@Injectable()
export class MyService {
constructor(private readonly cacheService:CacheService) { .. }
@UseCache('itemId')
async getItem(where): Promise<ItemModel> {
return this.ItemModel.find(where);
}
@UseCache('anotherCacheKey')
async anotherMethodWithCache(): Promise<any> {
// ...
}
}
推荐阅读
- android - 如何从 pfx 获得证书
- python - 找不到django下载文件
- python - 获取所有列对之间具有非 na 值的“周期”数的矩阵(联合计数)
- graph - BFS 回溯——孤立集群的情况
- html - 绝对位置不适用于导航栏中的详细信息摘要
- sas - SAS PROC DISCRIMS 中的密度含义
- python - 尝试使用 Session 时 Django 中的 JSON 可序列化问题
- python-3.x - Stan (pystan) 创建一个整数向量以分配给分类分布
- sql - 是否可以强制执行基于数据库完整性的间接关系
- postgresql - 从 clickhouse 连接 pSQL 时出错