Cache middleware — cache responses for performance.
1function cacheMiddleware(options = {}) {2 const {3 ttl = 60,4 keyGenerator = (req) => req.originalUrl,5 condition = () => true,6 } = options;78 const cache = new Map();910 return (req, res, next) => {11 if (!condition(req)) return next();1213 const key = keyGenerator(req);14 const cached = cache.get(key);1516 if (cached && Date.now() - cached.timestamp < ttl * 1000) {17 res.setHeader("X-Cache", "HIT");18 return res.json(cached.data);19 }2021 res.setHeader("X-Cache", "MISS");22 const originalJson = res.json.bind(res);2324 res.json = (data) => {25 cache.set(key, {26 data,27 timestamp: Date.now(),28 });29 return originalJson(data);30 };3132 next();33 };34}3536// Usage37app.get("/products",38 cacheMiddleware({39 ttl: 300,40 keyGenerator: (req) => `products:${req.query.page}`,41 condition: (req) => req.method === "GET",42 }),43 async (req, res) => {44 const products = await db.getProducts(req.query);45 res.json(products);46 }47);4849// Invalidate cache50app.post("/products", async (req, res) => {51 const product = await db.createProduct(req.body);52 cache.delete("products:1"); // invalidate53 res.json(product);54});