DedicatedDreamer
DedicatedDreamer

Reputation: 411

How do I cache a large array in Redis with a time interval in Node

I know how I can use node and redis with a middleware function to cache data when a request happens.

But now I would like to cache the complete state of my smartcontract at a one minute time interval. So I make the async request to get the smartcontract data on the backend in Node. Sort it, store the sorted array in Redis. And then acces it from my middleware. So it's always stored and updated and the client never has to wait until the smartcontract is fetched and sorted.

How would I go about this. I have no minimal reproducable example because I don't know where to start. I don't need the whole code just a quick pointer in the right direction. This is how I get the state of the smartcontract:

async function getMessages(req, res, next) {
  try {
    console.log(`Getting the entire contract state`);
    const contract = zilliqa.contracts.at(tokenContract);
    const allState = await contract.getState();
    var arr = []
    var sorted =
      Object.keys(allState.texts).forEach(function (key) {
        var value = allState.texts[key];

        Object.keys(value).forEach(function (key_two) {
          var value_two = value[key_two];

          Object.keys(value_two).forEach(function (key_three) {
            var value_three = parseInt(value_two[key_three]);
            var zil = value_three / 1000000000000;
            var rank = (parseInt(key_three) / 12000) * zil;
            arr.push({ 'zil': zil, 'text': key_two, 'address': key, 'block' : key_three, 'rank' : rank });
  
          });

        });
      });

    arr.sort(function (a, b) {
      return parseFloat(b.rank) - parseFloat(a.rank);
    }
    );
}

I would like to store arr in Redis after it is sorted. In a one minute time interval with a timer in node. Is this possible?

Thank you for your time

Upvotes: 0

Views: 734

Answers (1)

Petr Hejda
Petr Hejda

Reputation: 43521

For the interval, you can use setInterval(). A widely-used redis client package is simply named redis.

So combined:

const redis = require("redis");
const redisClient = redis.createClient(); // no arg = default options

const getMessages = async () => {
    const arr = [
        {'foo': 1},
        {'foo': 2}
    ];

    console.log(arr);
    redisClient.set("messages", arr);
}

setInterval(getMessages, 60 * 1000); // 60 sec * 1000 milisec
getMessages(); // so that you don't have to wait 60 sec for the first call from `setInterval()`

Upvotes: 1

Related Questions