Created
February 21, 2021 19:34
-
-
Save OtayNacef/f36b5a2161f37ffae4cb256de7f973e1 to your computer and use it in GitHub Desktop.
Express middleware caching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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