Skip to content

Syed007Hassan/Node-Redis

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Node-Redis-Cache

It is a NodeJS app which is using Redis to demonstrate caching. It consumes Harry Potter API for the demo purpose. A middleware function is used that stores the data in Redis using a key-value pair.

// cache data in redis
const cacheData = async (req, res, next) => {
  try {
    const characterId = req.params.id;
    let redisKey = "hogwarts-characters";
    if (characterId) {
      redisKey = `hogwarts-character-${req.params.id}`;
    }
    const cacheResults = await redisClient.get(redisKey);
    if (cacheResults) {
      res.send({
        fromCache: true,
        data: JSON.parse(cacheResults),
      });
    } else {
      next();
    }
  } catch (error) {
    console.error(error);
    res.status(404);
  }
}

Response without caching

image

Response time: 566 ms

Response with caching

image

Response time: 17 ms

About

API caching in NodeJS using Redis database

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published