Complete the code to create a cache object in Express middleware.
const cache = [1]();We use new Map() to create a cache object that stores key-value pairs efficiently.
Complete the middleware function to check if the cache has the requested URL.
function cacheMiddleware(req, res, next) {
if (cache.[1](req.url)) {
res.send(cache.get(req.url));
} else {
next();
}
}The Map object uses the has method to check if a key exists.
Fix the error in the middleware to store the response body in cache after sending it.
function cacheMiddleware(req, res, next) {
if (cache.has(req.url)) {
res.send(cache.get(req.url));
} else {
const originalSend = res.send;
res.send = function(body) {
cache.set(req.url, [1]);
originalSend.call(this, body);
};
next();
}
}The body parameter contains the response content to cache.
Fill both blanks to create a cache middleware that stores JSON responses.
function cacheMiddleware(req, res, next) {
if (cache.has(req.url)) {
res.json(cache.get(req.url));
} else {
const originalJson = res.json;
res.json = function([1]) {
cache.set(req.url, [2]);
originalJson.call(this, [1]);
};
next();
}
}The parameter data holds the JSON response body, which we store in cache before sending.
Fill all three blanks to implement cache middleware with expiration time.
const cache = new Map(); const cacheExpiry = new Map(); const CACHE_DURATION = 60000; // 1 minute function cacheMiddleware(req, res, next) { const now = Date.now(); if (cache.has(req.url) && cacheExpiry.get(req.url) > [1]) { res.send(cache.get(req.url)); } else { const originalSend = res.send; res.send = function([2]) { cache.set(req.url, [3]); cacheExpiry.set(req.url, Date.now() + CACHE_DURATION); originalSend.call(this, [2]); }; next(); } }
We compare the current time now to the stored expiry time. The body parameter is cached and sent.