DEV Community

Aditya sharma
Aditya sharma

Posted on

Let's cache with node-cache

This post was originally posted on my blog, if you like the content feel free to subscribe to my newsletter.

We all are aware of the fact that how a cache system can drastically increase the efficiency of any system, be it front-end or backend. As a developer, we are constantly looking for ways to make things ⚑ fast, and caching is the first thing that (should) comes to our mind.

Designing a caching system can be tricky depending upon the requirement and type. This post will majorly focus on application-level caching.

Intro

Application-level caching, putting it in simple words there will be an application-level system to provide already computed results, this can be used in both backend or front-end (in your controllers) if this sounds interesting let's do the deep dive.


const NodeCache = require( "node-cache" );
// Create an instance of NodeCache.
const myCache = new NodeCache();

// This checks if data exists in cache ?
myCache.get(myKeyName,function(err,value){
  if(!err){
      // If no error occured in checking.
      if(value== undefined || value==null){
          // If the do not exist in cache system, then we will get it from the main system.
          axios.get(`https://jsonplaceholder.typicode.com/todos/${id}`)
          .then(response=>{
              // Set the obtained result for next call.
              myCache.set(todoKey,response,function(err, doc){
                  resolve(response)                        
              })
          })
      }else{
          // Got the data in cache, no need to call main system.
          resolve(value);
      }
  }else {
      reject('error occured')
  }
})

One major need of any caching system is to invalidate the cache, just to flush the new data. For this, we can do something like this.

myCache.flushAll()

That's it.

Some examples where you can use this caching system:-

  • You have static offers to show on any page, which are not changing too frequently.
  • You have fixed data for specific route pairs.
  • You have fixed ratings and reviews for specific items.

Thanks for reading, you have been a fantastic reader. Keep coming back 😊
Subscribe to my newsletter.

Top comments (0)