Wednesday, 8 January 2020

How to create a re-usable caching method while using node-cache

I'm using node-cache on my Node.JS & Express web service. But after a while, I've got a bunch of similar logics cluttering, like these:

let data = this.cache.get('some-key')
if (data) {
    return shopInfo
} else {
    data = someModel.find(id)
    this.cache.set('some-key', data)
    return data
}

I Googled about it and found a possible solution here. But I don't wanna pass a callback function every time. Is there a better way? Or how can I modify it to utilize async/await instead of callback function?

get(key, storeFunction) {
    const value = this.cache.get(key);
    if (value) {
      return Promise.resolve(value);
    }

    return storeFunction().then((result) => {
      this.cache.set(key, result);
      return result;
    });
}


from How to create a re-usable caching method while using node-cache

No comments:

Post a Comment