i want to access the data of response in nodejs .
i have middllware for cache in redis . if data has exist in redis , it return data if not exists it go to database and return data .
my problem is when data not exist in database .
i want when data not exist in redis , get data from data base and when send data to client , set data to redis .
i create a middlware for redis cache :
module.exports = new (class RedisMiddllware {
Cache(req, res, next) {
redis.Get(req.path).then((response)=>{
if (response !== null) {
new OkObjectResult(response).Send(res);
} else {
next();
}
}).catch((error)=>{
throw new Error(error)
})
}
})();
i want set data after next();
in redis but when i use the res
it not show me return data .
i return data by this way :
res.status(400).json({
message: success,
data:{
"isDelete": false,
"_id": "5f4134984cb63a0ca49a574d",
"name": "Farsi",
"flag": "IR",
"unit": "Rial",
"createDate": "Sat Aug 22 2020 19:37:04 GMT+0430 (Iran Daylight Time)",
"createBy": "kianoush",
"__v": 0,
"updateBy": "kianoush",
"updateDate": "Sat Aug 22 2020 20:38:23 GMT+0430 (Iran Daylight Time)",
"deleteDate": "Sun Aug 23 2020 13:31:07 GMT+0430 (Iran Daylight Time)",
"deleteby": "kianoush",
"id": "5f4134984cb63a0ca49a574d"
},
statusCode:200,
success: true,
});
how can i access to result data in middllware after next()
from resonse ???
2
Answers
NodeJS middleware execute independently, in order and stops executing as soon as one does a "response.send()" or equivalent. Put simply if you have 3 middleware functions (md1, md2, md3) in defined on an endpoint. Then then Node will call md1 first and if md1 does a "response.send()" then md2 and md3 are not called at all. If md1 does a "next()" then md2 is called, but it has no knowledge of md1. Also, it is not like function call tree, where the control comes back to md1 after md2 has executed.
With all the theory out of the way, you need to put the result into the Redis cache after you have got it from the database, in the same function where you are ding the database call and probably doing a "response.json()" as well.
Please take a look at the REPL : https://unselfishvoluminouscad.deepakchampatir.repl.co
It doesn’t use a Redis cache, but you will find the necessary logic to accomplish what you want.
How can I access result data in middleware after
next()
from response ???Answer: No you cannot,
next()
is the end of that function. You have to save to Redis the next function which is called.