Skip to content

Instantly share code, notes, and snippets.

@haidarafif0809
Last active October 18, 2022 19:19
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save haidarafif0809/5c29004acdef108b9610c7567ac63960 to your computer and use it in GitHub Desktop.
Save haidarafif0809/5c29004acdef108b9610c7567ac63960 to your computer and use it in GitHub Desktop.
Redis Middleware using in nodejs express js.
const redis = require("redis");
const redis_url = process.env.REDIS_URL || null;
const client = redis.createClient(redis_url);
module.exports = {
getCached: (req, res, next) => {
const { redis_key } = req.headers
client.get(redis_key, function(err, reply) {
if (err) {
res.status(500).json({
message: "Somethin Went Wrong"
})
}
if (reply == null) {
next()
} else {
res.status(200).json({
message: `Success Read ${redis_key}`,
data: JSON.parse(reply)
})
}
});
},
caching: (key, data) => {
client.set(key, JSON.stringify(data) )
},
delCache: (key) => {
client.del(key)
}
}
@TASKMASTER682
Copy link

hello brother, how to use this middleware. it is not a function?

@payn33
Copy link

payn33 commented Feb 1, 2022

yeah it is, You pass it to your route before the controller something like router.get('/url', getCached, controller.control). he's exporting as an object so i think you destructure the import

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment