Created
August 20, 2019 12:55
-
-
Save bradtraversy/a9dedcdf4350fd417819ee6538482aae to your computer and use it in GitHub Desktop.
Node.js & Redis 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
const express = require('express'); | |
const fetch = require('node-fetch'); | |
const redis = require('redis'); | |
const PORT = process.env.PORT || 5000; | |
const REDIS_PORT = process.env.PORT || 6379; | |
const client = redis.createClient(REDIS_PORT); | |
const app = express(); | |
// Set response | |
function setResponse(username, repos) { | |
return `<h2>${username} has ${repos} Github repos</h2>`; | |
} | |
// Make request to Github for data | |
async function getRepos(req, res, next) { | |
try { | |
console.log('Fetching Data...'); | |
const { username } = req.params; | |
const response = await fetch(`https://api.github.com/users/${username}`); | |
const data = await response.json(); | |
const repos = data.public_repos; | |
// Set data to Redis | |
client.setex(username, 3600, repos); | |
res.send(setResponse(username, repos)); | |
} catch (err) { | |
console.error(err); | |
res.status(500); | |
} | |
} | |
// Cache middleware | |
function cache(req, res, next) { | |
const { username } = req.params; | |
client.get(username, (err, data) => { | |
if (err) throw err; | |
if (data !== null) { | |
res.send(setResponse(username, data)); | |
} else { | |
next(); | |
} | |
}); | |
} | |
app.get('/repos/:username', cache, getRepos); | |
app.listen(5000, () => { | |
console.log(`App listening on port ${PORT}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Instal the used version so you don't have to worry about importing it in a different way.
npm i [email protected]