ExpressJs makes a callback after sending a response for each route
The scenario is to store data in the cache. We have numerous express routes written with complex logic.
I need to find a way to store the response data in the cache. I cant go down every route and check if it needs to store and save the data before sending the response. (If no one else goes, then it might be)
I've tried the following approaches.
- https://nodejs.org/api/http.html#http_event_close_1 - using 'close' or 'finish' that fires after sending a response will do the trick. But I cannot get the response data in these events.
- Also my node version is v0.10.31
- Thought about using app.all ('*', callback) , but I'm not sure how to catch the response data for caching.
- Finally, I thought about adding a second callback for routing, app.VERB (path, [callback ...], callback) , but after returning the response on the first callback, the second callback is never called.
Hoping there is a solution for this and I've been stuck on this for over a week.
The reason adding logic to each route is a tedious job is because I need to add a config entry specifying which route to cache with expiration.
The response needs to be cached on the redis server . The cache key will be generated based on route data and query strings. All this complete user information will be stored in the key.
This way, when the user types the same route, a key will be generated to check if it exists using app.use , and the data will be served without prior staging environments.
source to share
Define callback middleware as
var storeResponseMiddleware = function(req, res, next) {
console.log("storing data in redis....")
..........more stuff
}
Add it to expressJs app like,
app.use(logicRoute)
app.use(storeResponseMiddleware)
Now for all responses storeResponseMiddleware
will be called. you must call next()
inside route handlers.
source to share