Created
August 5, 2023 21:37
-
-
Save finwo/e82ce510b5673039269218185bad41b6 to your computer and use it in GitHub Desktop.
Caching thingymagic
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 app = require('express')(); | |
const fetch = require('node-fetch'); | |
const port = parseInt(process.env.PORT || '8080'); | |
const cache = {}; | |
app.get('/:packageName', async function(req, res) { | |
const now = Date.now(); | |
if (cache[req.params.packageName] && (cache[req.params.packageName].exp > now)) { | |
const cacheData = cache[req.params.packageName].data; | |
res.send(`Current version: ${cacheData.name}`); | |
return; | |
} | |
const response = await fetch('https://api.github.com/.......', { | |
headers: { | |
Authorization: '...', | |
} | |
}); | |
const responseData = await response.json(); | |
cache[req.params.packageName] = { | |
exp : now + (3600 * 1000), | |
data: responseData, | |
}; | |
res.send(`Current version: ${responseData.name}`); | |
}); | |
app.listen(port, function(err) { | |
if (err) throw err; | |
console.log(`Server listening on :${port}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment