Complete the code to set a cache expiration time in Express middleware.
app.use((req, res, next) => {
res.set('Cache-Control', 'public, max-age=[1]');
next();
});The max-age directive sets the cache expiration time in seconds. Here, 3600 means the cache expires after one hour.
Complete the code to clear a specific cache key in an Express route.
app.get('/clear-cache', (req, res) => { cache.[1]('user-data'); res.send('Cache cleared'); });
The delete method removes a specific key from the cache.
Fix the error in the cache middleware to properly invalidate cache after response.
app.use((req, res, next) => {
res.on('finish', () => {
cache.[1](req.originalUrl);
});
next();
});The delete method is used to remove the cache entry for the requested URL after the response finishes.
Fill both blanks to create a cache middleware that skips caching for authenticated users.
app.use((req, res, next) => {
if (req.user && req.user.[1]) {
res.set('Cache-Control', '[2]');
}
next();
});The middleware checks if the user is authenticated using isAuthenticated. If true, it sets Cache-Control to no-store to prevent caching sensitive data.
Fill all three blanks to implement a cache invalidation strategy that clears cache on data update.
app.post('/update-data', (req, res) => { updateDatabase(req.body); cache.[1](req.body.[2]); res.status(200).send({ message: '[3]' }); });
After updating the database, the cache entry identified by id is deleted using delete. Then a success message is sent.