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