typescriptintermediate
In-Memory Response Cache
Simple TTL-based in-memory cache middleware for GET endpoints that serves cached responses.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { Request, Response, NextFunction } from 'express';
interface CacheEntry {
body: unknown;
expiry: number;
}
const cache = new Map<string, CacheEntry>();
export function cacheMiddleware(ttlSeconds = 60) {
return (req: Request, res: Response, next: NextFunction) => {
if (req.method !== 'GET') return next();
const key = req.originalUrl;
const cached = cache.get(key);
if (cached && cached.expiry > Date.now()) {
res.setHeader('X-Cache', 'HIT');
return res.json(cached.body);
}
const originalJson = res.json.bind(res);
res.json = function (body: unknown) {
cache.set(key, { body, expiry: Date.now() + ttlSeconds * 1000 });
res.setHeader('X-Cache', 'MISS');
return originalJson(body);
};
next();
};
}Use Cases
- Caching expensive queries
- Reducing database load
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptadvanced
Redis Cache Get/Set Helper
Type-safe Redis cache wrapper with automatic JSON serialization, TTL support, and cache-aside pattern.
Best for: Database query caching
#redis#cache
pythonintermediate
LRU Cache with TTL Support
Extend functools.lru_cache with time-based expiration for caching expensive function calls with staleness control.
Best for: Database query caching
#cache#lru
pythonintermediate
Optimize Memory with __slots__
Reduce memory usage for classes with many instances using __slots__.
Best for: Memory-constrained applications
#python#slots
javaintermediate
String Pool and Interning
Understand Java string pooling: intern(), identity vs equality, memory optimization, and common pitfalls.
Best for: Memory optimization for repeated string values
#java#string