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
3
Answers
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.
Wait until client connected to the server and then export it
This error is most likely because
client
isundefined
. This suggests that yourimport
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 runnpm 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:
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.