When I npm start the express server and go to localhost:3000/
There will be error message: (node:6984) UnhandledPromiseRejectionWarning: Error: The client is closed
The redisClient will be working when I put the createClient() in App.js, however, I want to make connect to the redis once and all files able establish the same connection
"redis": "^4.0.4"
"express": "^4.17.3"
App.js
const express = require('express');
const port = 3000;
const { getData} = require('./utils/data');
const app = express();
app.get('/', (req, res) => {
getData()
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
./utils/data.js
const axios = require('axios');
const redisClient = require('../controllers/redis');
const getData= async() => {
redisClient.get("getData", async(error, data) => {
if (error) console.log(error);
if (data != null) {
return res.json(JSON.parse(data));
} else {
axios.get(`http://api.com`)
.then((res) => {
redisClient.set("getLeague", JSON.stringify(res.data));
res.json(res.data);
});
}
});
};
exports.getData= getData;
./controllers/redis.js
const redis = require('redis')
const redisClient = redis.createClient()
redisClient.on('connect', function () {
console.log('redis client connected');
});
module.exports = redisClient;