-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.js
50 lines (42 loc) · 1.39 KB
/
router.js
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
const express = require('express');
const fetch = require('node-fetch');
const cacheController = require('./middleware/cacheController');
const cache = require('./cache');
const router = express.Router();
router.get('/user/:username',
cacheController.getUserDetails,
cacheController.getUserDetailsFromHash,
async (req, res) => {
const {username} = req.params;
const {field} = req.query;
const response = await fetch(`https://api.github.com/users/${username}`);
const data = await response.json();
cache.addToCache(username, JSON.stringify(data), 3600);
let convertedData;
convertedData = Object.entries(data).reduce((array, [k, v]) => {
if (!v) {
if (v === 0) {
v = '0'
} else {
v = ''
}
}
array.push(k, v);
return array;
}, []);
cache.addToHash(`${username}fields`, convertedData)
if (field) {
let responseData = [];
if (typeof field === "string") {
responseData.push(data[field]);
} else {
field.forEach(key => {
responseData.push(data[key]);
})
}
res.json(responseData);
} else {
res.json(data);
}
})
module.exports = router;