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 as GET /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)
}
}
})
});