skip to Main Content

This is my server call to route

const redis = require("redis");
const client = redis.createClient();
client.connect();
module.exports = client;

This is my API route

app.get("/api/ping", middleWare.cacheRouteOne, RouteController.routeOne);

This is my cache route function

exports.cacheRouteOne = (req, res, next) => {
  client.get("ping", (err, data) => {
console.log(data);//To check whether is working or not.
 if (err) throw err;
if (data != null) {
  res.json({
 postss: JSON.parse(data),
 });

} else {
  next();
    }
  });
};

And this is my API call code

exports.routeOne = (req, res) => {
  axios
    .get("some APi CALL")
    .then((response) => {
      client.setEx("ping", 3600, JSON.stringify(response.data.posts));
      console.log(client);

      res.status(200).json({

        status: true,

        posts: response.data.posts,

      });

    });

};

When it calls the middle function it hangs my code after clinet.get()

2

Answers


  1. Chosen as BEST ANSWER

    I got the answer, I was making a call back but for forget to add await , so this is the updated middleware code

    exports.cacheRouteOne = async (req, res, next) => {
      let data = await client.get("ping");
      console.log("data of ping");
      if (data != null) { 
        res.json({
          postss: JSON.parse(data),
        });
        console.log("yes");
      } else {
        next();
      }
    };
    

  2. use this code to connect redis

    const client = redis.createClient({
        socket: {
          port: 6379,
          host: "127.0.0.1",
        }
      });
    
    (async () => {
        // Connect to redis server
        await client.connect();
    })();
    
    
    console.log("Attempting to connect to redis");
    client.on('connect', () => {
        console.log('Connected!');
    });
    
    // Log any error that may occur to the console
    client.on("error", (err) => {
        console.log(`Error:${err}`);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search