skip to Main Content

This is my code for the get function of Redis. When sending the gameid, it’s not working, but when using hardcoded values, it’s working. I don’t know what I am doing wrong.

const redis = require("redis");

const client = redis.createClient({
  url: "redis://localhost:6379",
});

// Handle Redis client errors
client.on("error", (err) => {
  console.error("Redis error:", err);
});

// Connect to Redis
(async () => {
  try {
    await client.connect();
    console.log("Connected to Redis");
  } catch (err) {
    console.error("Failed to connect to Redis:", err);
  }
})();

const testRedis = async (game_id) => {
  try {
    console.log(`Getting value for key: game:${game_id}`);
    const value = await client.get(`game:${game_id}`);
    if (value === null) {
      console.log(`No value found for key game:${game_id}`);
    } else {
      console.log("Value:", value);
    }
  } catch (err) {
    console.error("Redis test error:", err);
  } finally {
    console.log("Quitting Redis client...");
    await client.quit();
    console.log("Redis client closed.");
  }
};

module.exports = {
  testRedis,
};

Here is my route code:

router.get("/game", async (req, res) => {
  const { game_id } = req.query;
  console.log(`Fetching game data for game_id: ${game_id}`);
  try {
    const gameData = await testRedis(game_id);
    if (gameData) {
      res.status(200).json(JSON.parse(gameData));
    } else {
      res.status(404).json({ error: "Game not found" });
    }
  } catch (err) {
    console.error("Error fetching game from Redis:", err);
    res.status(500).json({ error: "Internal server error" });
  }
});

Here is the output which I get when using hardcoded values:

Getting value for key: game:U2WQ20

Value: {"game_id":"U2WQ20","users":[{"username":"nikhil","cards":["0_5","3_3","1_3","1_8","3_13"] },{"username":"john","cards":["3_4","1_10","0_9","1_11","0_13"]},{"username":"jane","cards":["3_9 ","3_2","1_12","3_12","1_9"]}],"play_deck":["2_5","2_7","3_11","2_8","2_4","0_12","1_2","1_6","2_ 12","1_1","3_5","3_7","2_9","0_1","0_6","1_5","0_3","0_10","1_13","2_3","2_11","2_13","3_1","0_7" ,"0_2","1_7","2_2","3_10","0_11","1_4","0_4","2_1","2_10","3_8","2_6","3_6"],"firstCard":"0_8"}


Quitting Redis client... Connected to Redis Redis client closed.

Here is the output which I get when using game ID from request query :

Server started on port 8080 Connected to Redis Fetching game data for game id: U2WQ20

Getting value for key: game:U2WQ20

No value found for key game:U2WQ20

Quitting Redis client... Redis client closed.

2

Answers


  1. Chosen as BEST ANSWER
        const redis = require('redis');
    const express = require("express");
    const { isAuthenticated } = require("../auth/middleware");
    const router = express.Router();
    router.use(express.json());
    
    // Create and configure the Redis client
    const client = redis.createClient({
      url: 'redis://localhost:6379'
    });
    
    client.on('error', (err) => {
      console.error('Redis error:', err);
    });
    
    // Ensure the client is connected when the application starts
    (async () => {
      try {
        await client.connect();
        console.log('Redis client connected.');
      } catch (err) {
        console.error('Error connecting to Redis:', err);
      }
    })();
    
    const testRedis = async (game_id) => {
      try {
        console.log(`Getting value for key: ${game_id}`);
        const value = await client.get(game_id);
        if (value === null) {
          console.log(`No value found for key ${game_id}`);
          return null;
        } else {
          console.log('Value:', value); // Should print the JSON string
          return value;
        }
      } catch (err) {
        console.error('Redis test error:', err);
        throw err;
      }
    };
    
    // Endpoint to fetch game data
    router.get("/game", async (req, res) => {
      const { game_id } = req.query;
      console.log(`Fetching game data for ${game_id}`);
      try {
        const gameData = await testRedis(game_id);
        if (gameData) {
          res.status(200).send(gameData);
        } else {
          res.status(404).json({ error: "Game not found" });
        }
      } catch (err) {
        console.error('Error fetching game from Redis:', err);
        res.status(500).json({ error: "Internal server error" });
      }
    });
    
    module.exports = router;
    

    This is giving me the correct expected output. When putting both the files in one single file it's working.


  2. I don’t think the code in different files is the issue. May be something is missed while import. Your code is absolutely fine. You just had to return the value. This is what I did, and it is working for me.

    Update the redis value first:

    % redis-cli
    127.0.0.1:6379> set game:U2WQ20 '{"game_id":"U2WQ20","users"
    [{"username":"nikhil","cards:
    ["0_5","3_3","1_3","1_8","3_13"] },
    {"username":"john","cards":
    ["3_4","1_10","0_9","1_11","0_13"]}
    ,{"username":"jane","cards":["3_9 
    ","3_2","1_12","3_12","1_9"]}],"play_deck":
    ["2_5","2_7","3_11","2_8","2_4","0_12","1_2","1_6","2_     12","1_1","3_5","3_7","2_9","0_1","0_6","1_5","0_3","0_10","1_13","2_3","2_11","2_13","3_1","0_7" ,"0_2","1_7","2_2","3_10","0_11","1_4","0_4","2_1","2_10","3_8","2_6","3_6"],"firstCard":"0_8"}'
    
    OK
    

    Main file: Index.js

    const express = require('express');
    const { testRedis } = require('./redis');
    const app = express();
    
    // Define routes and middleware here
    // ...
    
    app.get("/game", async (req, res) => {
        const { game_id } = req.query;
        console.log(`Fetching game data for game_id: ${game_id}`);
        try {
          const gameData = await testRedis(game_id);
          if (gameData) {
            res.status(200).json(JSON.parse(gameData));
          } else {
            res.status(404).json({ error: "Game not found" });
          }
        } catch (err) {
          console.error("Error fetching game from Redis:", err);
          res.status(500).json({ error: "Internal server error" });
        }
      });
    
    const PORT = process.env.PORT || 3011;
    app.listen(PORT, () => {
        console.log(`Server running on port ${PORT}`);
    });
    

    Redis functions in redis.js file:

    const redis = require("redis");
    
    const client = redis.createClient({
      url: "redis://localhost:6379",
    });
    
    // Handle Redis client errors
    client.on("error", (err) => {
      console.error("Redis error:", err);
    });
    
    // Connect to Redis
    (async () => {
      try {
        await client.connect();
        console.log("Connected to Redis");
      } catch (err) {
        console.error("Failed to connect to Redis:", err);
      }
    })();
    
    const testRedis = async (game_id) => {
      try {
        console.log(`Getting value for key: game:${game_id}`);
        const value = await client.get(`game:${game_id}`);
        if (value === null) {
          console.log(`No value found for key game:${game_id}`);
        } else {
          console.log("Value:", value);
        }
        return value;
      } catch (err) {
        console.error("Redis test error:", err);
      } finally {
        console.log("Quitting Redis client...");
        await client.quit();
        console.log("Redis client closed.");
      }
    };
    
    module.exports = {
      testRedis,
    };
    

    Make sure the relative path is correct. In my case both the files are in the same root folder.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search