Day 36-39 ๐Ÿ‘‰ Do you store objects in Node-cache?. You need to see this.

Day 36-39 ๐Ÿ‘‰ Do you store objects in Node-cache?. You need to see this.

ยท

2 min read

Hello Guys ๐Ÿ‘‹

Due to the instability of power supply over here, I wasn't productive enough. But thank God, I'm still able to deliver.

On these days, I drafted workflows, wrote, review and rectify actual codes, and more.

Moreover, On the 38th, I encountered a bug and I learnt something very important from it. I wanted to store an object in a cache storage (node-cache) directly. It was so hectic, I was frustrated by the repeated error messages.

Let's take a little dive into it (NODE-CACHE)

It will one day save someone from spending hours stressing the brain due to some minor bugs.

First of all, we need to understand that the node-cache module in Node.js is primarily designed to cache key-value pairs, where both the key and value are strings. If you attempt to store an object directly as a value, it will implicitly get converted to a string using toString() before being stored. When you retrieve the value, you'll get back the string representation of the object, not the original object itself.

Secondly, there are scenarios where objects (complex objects) may not behave as expected when converted to strings. And because you don't know that node-cache is string based, you fall into problem that might take hours.

Here are ways to solve the problem ๐Ÿ‘‡๐Ÿ‘‡

  • Serializing the object to JSON using JSON.stringify() before caching it and deserializing it back to an object when retrieving.

      const NodeCache = require("node-cache");
      const myCache = new NodeCache();
    
      // Storing object
      const myObject = {
        name: 'John',
        age: 30,
        sayHello() {
          return `Hello, my name is ${this.name}.`;
        }
      };
    
      const serializedObject = JSON.stringify(myObject);
      myCache.set("myKey", serializedObject);
    
      // Retrieving object
      const retrievedObject = myCache.get("myKey");
      if (retrievedObject) {
        const deserializedObject = JSON.parse(retrievedObject);
        console.log(deserializedObject); // { name: 'John', age: 30, sayHello() { return `Hello, my name is ${this.name}.`;} };
      }
    
  • Using alternative caching mechanisms like memory-cache or redis, which offer support for storing complex objects directly. Infact, this is better when it comes to complex objects. no stress.

Feel free to correct me if I'm wrong allahisrabb. ๐Ÿ™.

Thanks. God bless.

ย