Home > OS >  can't read properties for SET/GET in redis and node.js
can't read properties for SET/GET in redis and node.js

Time:10-29

I just start to explore redis. I want to cache some data using redis. I set up redis connection in the server.ts file and export it from there. Import it in my controller function and try to use set and get but this error comes for both get and set.

TypeError: Cannot read properties of undefined (reading 'get')
//sever.js---> redis connection part
export const client = redis.createClient({
  url: "redis://127.0.0.1:6379",
});

client.connect();
client.on("error", (err) => console.log("Redis Client Error", err));

const app: Application = express();
//controller

import { client } from "../server";

const allProjects = async (req: Request, res: Response): Promise<void> => {
  const cachedProjects = await client.get("projects");
  if (cachedProjects) {
    res.status(200).json(JSON.parse(cachedProjects));
  }
  const projects = await Projects.find({});
  if (!projects) {
    res.status(400).send("No projects found");
    throw new Error("No projects found");
  }
  await client.set("projects", JSON.stringify(projects));
  res.status(200).json(projects);
};

My Redis server is running and I can use set/get using redis cli. I make a mistake somewhere but can't find it.

I am using Node.js, Express.js and Typescript

CodePudding user response:

This error is most likely because client is undefined. This suggests that your import from server.js isn't doing what you think it is. This could be because server.js is special from a Node.js point of view as it's the default file that loads when you run npm start. Might be better to put that code in its own file.

To test this, try doing a .get and .set in server.js after your connection is established and see if that works. If so, you've proved you can talk to Redis. The rest is debugging.

Also, you might want to refer to the example code on the Node Redis Github repo. I've added it here for your convenience:

import { createClient } from 'redis';

const client = createClient();

client.on('error', (err) => console.log('Redis Client Error', err));

await client.connect();

await client.set('key', 'value');
const value = await client.get('key');

Note that Alexey is right that you need to await the establishment of a connection. You should also add the error handler before doing so. That way if establishing a connection fails, you'll know about it.

CodePudding user response:

Wait until client connected to the server and then export it

//sever.js---> redis connection part
const client = await redis.createClient({
  url: "redis://127.0.0.1:6379",
});

await client.connect();
client.on("error", (err) => console.log("Redis Client Error", err));

const app: Application = express();
export client

CodePudding user response:

I find the solution. Actually, I write the Redis server connection code in the wrong place. It should be after all path. Then it works fine.

app.use("/api/v1/uploads", imageUpload);
app.use("/api/v1/forgetPassword", forgetPassword);
app.use("/api/v1/resetPassword", resetPassword);

app.use("/uploads", express.static(path.join(dirname, "/uploads")));

client.connect();
client.on("connected", ()=> console.log("Redis connected"))
client.on("error", (err) => console.log("Redis Client Error", err));

app.use(notFound);

var server = app.listen(process.env.PORT || 3001, () =>
  console.log(`Listening on port ${process.env.PORT}`)
); 

  • Related