-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
57 lines (41 loc) · 1.28 KB
/
Copy pathindex.js
File metadata and controls
57 lines (41 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
const express = require('express');
const fetch = require('node-fetch');
const redis = require('redis');
const PORT = process.env.PORT || 5000;
const REDIS_PORT = process.env.REDIS_PORT || 6379;
const client = redis.createClient(REDIS_PORT);
const app = express();
//set Response
function setResponse(username,repos){
return `<h2>${username} has ${repos} github repositories</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;
client.setex(username,3600,repos);
res.send(setResponse(username,repos));
} catch (err) {
console.error(err);
res.status(500);
}
}
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}`);
});