1

I'm trying to create a basic caching app just to test redis. Im using Redis Version: 4.0.6.

First I was getting error clientclosederror: the client is closed.

Then, after reading the docs, I added

let client;
(async ()=> {
 client = redis.createClient()
 await client.connect()
 
})(); 

But now, when trying on Postman, it just hangs, no response is returned

Full Code:

const express = require("express");
const redis = require("redis");
const axios = require('axios')
const app = express();
let client;
(async ()=> {
 client = redis.createClient()
 await client.connect() 
})(); 
app.get('/result', async (req, res) => {
 const searchTerm = req.query.name; 
 try {
 await client.get(searchTerm, async (err, result) => {
 console.log('cached called')
 if (err) throw err;
 if (result) {
 res.status(200).send({
 result: JSON.parse(result),
 message: "data retrieved from the cache"
 });
 }
 else {
 const result = await axios.get(`https://api.agify.io/?name=${searchTerm}`);
 await client.set(searchTerm, JSON.stringify(result.data));
 
 return res.status(200).send({
 result: result.data,
 message: "cache miss"
 });
 }
 })
 } catch (error) {
 console.log('get error', error)
 return res.status(500).send({ message: error.message })
 }
})
app.listen(process.env.PORT || 3000, () => {
 console.log("Node server started");
});
asked Apr 25, 2022 at 16:59

1 Answer 1

1

client.get doesn't need a callback function. It's async. My guess is that it's never getting called and thus Express is not returning anything.

Try this instead:

const result = await client.get('foo')
if (result !== null) {
 // it's a hit
} else {
 // it's a miss
}
answered Apr 25, 2022 at 17:11
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.