I’m using Express.js, and I want to initialize a cache on every initial request to a route, and on the subsequent ones use the cached value.
For now, I do something like this:
let hasRun = false;
app.get('/my-route', async (req, res) => {
if (!hasRun) {
await redisClient.set('key', {});
hasRun = true;
}
const data = await redisClient.get('key');
res.send(data );
});
But if I have multiple routes, it becomes kind of messy.
What do you suggest?
Note: Even though Redis allows checking if a value exists, I want to ensure the cache is always refreshed and initialized on the first access.
2
Answers
make middleware that checks a Redis cache to run initialization logic only once per route fetch and store data in Redis then serve cached data on future requests.
Example
The
runOnceForRoute
middleware checks if the cache has been initialized for a specific route key. If not, it calls the providedinitializationLogic
function to fetch and cache the data, and sets a flag in Redis to indicate that the initialization has been completed.For each route, we use the
runOnceForRoute
middleware to ensure that the cache is initialized only once. Inside the initialization logic, we callfetchAndCacheData
to fetch the data and cache it in Redis, and then retrieve the cached data and send it as the response.