首页 > 解决方案 > 有没有办法取消猫鼬查找执行并从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 函数,但我只是不确定如何使用它来完成此操作。

这些是我正在使用的版本:

标签: typescriptmongooseredisnestjs

解决方案


您可以创建一个方法装饰器,将逻辑移至:

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

推荐阅读