Skip to content

Instantly share code, notes, and snippets.

@othonalberto
Last active December 26, 2019 17:29
Show Gist options
  • Save othonalberto/d3993823ddb53c28d4775f36f50be6a2 to your computer and use it in GitHub Desktop.
Save othonalberto/d3993823ddb53c28d4775f36f50be6a2 to your computer and use it in GitHub Desktop.
const express = require('express');
const axios = require('axios');
const cachimo = require('cachimo');
const app = express();
const port = 3000;
const ONESEC = 1000;
const ONEMIN = ONESEC * 60;
const ONEHOUR = ONEMIN * 60;
app.listen(port, () => console.log(`Listening on port ${port}`));
app.get('/:lang/:page', function(req, resp) {
const lang = req.params.lang;
const page = req.params.page;
const key = buildKey(lang, page);
const cached = cachimo.get(key);
if (cached) {
console.log(`[CACHE HIT] on Lang ${lang} Page ${page}`);
return resp.json(cached);
}
console.log(`[CACHE MISS] on Lang ${lang} Page ${page}`);
requestOnApi(lang, page)
.then(response => {
const items = response.data.items;
const objs = items.map(item => buildItem(item));
cachimo.put(key, objs, ONEHOUR*4);
resp.json(objs);
})
.catch(error => {
const errorObj = {
'message' : error.message
};
if (error.response.status === 402) cachimo.put(key, errorObj, ONEMIN*15);
resp.status(error.response.status).json(errorObj);
})
});
function buildKey(lang, page) {
return `lang=${lang};page=${page}`;
}
function requestOnApi(lang, page) {
return axios.get(`https://api.github.com/search/repositories?q=language:${lang}&sort=stars&page=${page}`)
}
const buildItem = (item) => {
return {
'name' : item.name,
'stars' : item.stargazers_count,
'forks' : item.forks_count
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment