gpt4 book ai didi

typescript - 有没有办法取消mongoose find执行并从redis返回数据?

转载 作者:行者123 更新时间:2023-12-03 06:36:17 25 4
gpt4 key购买 nike

我正在尝试在 nest.js 中与 mongoose 一起实现 Redis 缓存,我正在寻找一种方法
在执行 find 或 findOne 之前先检查 redis 缓存并从 redis 返回数据
否则执行查询,将结果保存在redis中并返回结果。
我没有实现的原因 caching正如 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 函数
但我只是不确定如何使用。
这些是我正在使用的版本:
  • nestjs v7
  • Mongoose v5.10.0
  • 最佳答案

    您可以创建一个 method decorator将逻辑移至:

    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> {
    // ...
    }
    }

    关于typescript - 有没有办法取消mongoose find执行并从redis返回数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64598778/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com