有没有办法取消mongoosefind执行,从redis返回数据?

k4ymrczo  于 2021-06-09  发布在  Redis
关注(0)|答案(1)|浏览(315)

我正在尝试在nest.js中实现redis cache和mongoose,我正在寻找一种方法,在执行find或findone之前先检查redis cache,然后从redis返回数据,否则执行query,将结果保存到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
mongoose 5.10.0版

monwx1rj

monwx1rj1#

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

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

相关问题