Jos*_*ván 5 mongoose redis typescript nestjs
我正在尝试在 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
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想将这段代码移到一个地方,这样我就不必为代码中的每个查询重复这段代码,因为我有多个服务。我知道 mongoose 中间件有一种方法可以在查询上运行 pre 和 post 函数,但我不确定如何使用它来完成此操作。
这些是我正在使用的版本:
您可以创建一个方法装饰器,将逻辑移动到:
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;
};
}
Run Code Online (Sandbox Code Playgroud)
然后将其与以下命令一起使用:
@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> {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
231 次 |
| 最近记录: |