Hello Fakorede Abiola,
Thanks you for your response. After reading it and the code again and again, I understand that I've missed a point: app.route take as many middleware as we want.
Your cache middleware is scoped here and not global to all the app:
app.get('/repos/:username', cache, async (req, res) => {
So everythings is good. Thanks again for your article, this is a great discovery for me :)
Hello,
Thanks a lot for this article π
Some though: IMHO, it's better if cache is agnostic. I mean if developers doesn't have to worry about how and what is cached while developing api.
Another thing: I don't understand why you put the cache retrieve code in a middleware. I might be wrong, but right now, if I query
GET /lmao/:username, and if the cache exist, looks like it will return me the same response asGET /repos/:username.So why not putting all the cache logic inside the cached route. I.E
app.get('/repos/:username', cache, async (req, res) => { const { username } = req.params client.get(username, (err, data) => { if (err) throw err if (data !== null) { res.send(data) } else { try { const response = await fetch(`api.github.com/users${username}/repos`) const data = await response.json() let repos = data.map(item => item.name) // save the repos to redis using the username as key and with an expiration client.setex(username, 60, repos) res.send(repos) } catch (err) { res.status(500) } } }) });