Skip to content

Instantly share code, notes, and snippets.

@OtayNacef
Created February 21, 2021 19:34
Show Gist options
  • Save OtayNacef/f36b5a2161f37ffae4cb256de7f973e1 to your computer and use it in GitHub Desktop.
Save OtayNacef/f36b5a2161f37ffae4cb256de7f973e1 to your computer and use it in GitHub Desktop.
Express middleware caching
import { Response, Request, NextFunction } from 'express';
import * as redis from 'redis';
const portRedis = process.env.PORT_REDIS || '6379';
const redisClient = redis.createClient(portRedis);
const isCached = (req: Request, res: Response, next: NextFunction) => {
const { idUser } = req.params;
// getting our data by key (id)
redisClient.get(idUser, (err, data) => {
if (err) {
res.status(500).send(err);
}
if (data != null) {
console.log('we Found it in Redis 🟢');
res.send(data);
} else {
console.log('User Not Found 🔴 ');
// go To ⏭️ function or middleware
next();
}
});
};
export default isCached;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment