Am trying to learn redis, am fetching github repo data, and then i want to cache it with redis. but i’m getting error why trying to use redis:
redis-and-fetch/node_modules/@redis/client/dist/lib/client/index.js:409
return Promise.reject(new errors_1.ClientClosedError());
ClientClosedError: The client is closed
this is my code
import express from "express";
import Redis from "redis";
import fetch from "node-fetch";
const PORT = process.env.PORT || 5000;
const REDIS_PORT = process.env.REDIS_PORT || "6379";
const client = Redis.createClient(REDIS_PORT);
const app = express();
// Set response
function setResponse(username, repos) {
return `<h2>${username} has ${repos} Github repos</h2>`;
}
// Make request to Github for data
async function getRepos(req, res, next) {
try {
console.log("Fetching Data...");
const { username } = req.params;
const response = await fetch(`https://api.github.com/users/${username}`);
const data = await response.json();
const repos = data.public_repos;
// Set data to Redis
// await client.connect();
client.setEx(username, 3600, repos);
res.send(setResponse(username, repos));
} catch (e) {
console.log(e);
res.status(500);
}
}
app.get("/repos/:username", getRepos);
app.listen(5000, () => {
console.log(`App listening on port ${PORT}`);
});
how can i fix this error?
2
Answers
If you take a gander at the README for Node Redis, you will find this bit of sample code:
This works find if you want to connect to Redis running locally and on the default port. If you want to connect to somewhere else, the client configuration guide shows you how. A couple of common ways are shown below:
I had the same issue with redis when using version 4.2.0 there are two changes required in order for the error to be solved.
to get the cached data run
const data = await client.get(username);