node.jscachingredisioredis

How to add dictionary/map inside redis using ioredis?


I am using ioredis library to rate limit the apis. Now I am trying to implement cache for recent accessed images(LRU) of size x, I am wondering if there is a way to add dictionary as value in the key-value pair(where key would be the userid). It would pop the older images and maintain the size of cache as x.

For example each user could have a cache of 5 images in form of -

userId -> [{imgId:1, data:{}} , {imgId:2, data:{}} ...]

Here is my getImagewithId controller

const getImagewithId = async (req, res) => {
  const id = parseInt(req.params.id);
  const key = `${req.user.id}/images`;
  // todo : implement cache using ioredis 
  const image = await prisma.image.findUnique({
    where: {
      id: id,
    },
  });
  if (!image) return res.status(404).json({ error: 'Image not found' });
  if (image.userId != req.user.id)
    return res.status(403).json({ error: 'Forbidden' });

  return res.status(200).json({ image: image });
};

Solution

  • I'm not a JavaScript developer, so I can't provide the exact implementation, but I can point you in the right direction.

    You should use the Redis HSET command, which allows you to store key-value pairs within a single hash. This way, you can associate multiple images with a single user ID.

    A Redis console example would look like this:

    HSET userId imgId1 data1 imgId2 data2 ...
    

    To retrieve an image by its ID, use the HGET command:

    HGET userId ImgId1
    

    After giving it some more thought, I’d suggest using regular keys with TTL if you need automatic cache cleanup. This way, Redis will handle expiration for you.

    For example:

    SET userId:imgId1 data1 EX timeout
    SET userId:imgId2 data2 EX timeout
    

    Here, data1 is stored under the key userId:imgId1, and it will be automatically removed from Redis after the specified timeout. This eliminates the need for manual cache cleanup, which would be required when using HSET.