forked from sagarkarira/coronavirus-tracker-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
91 lines (81 loc) · 2.51 KB
/
api.js
File metadata and controls
91 lines (81 loc) · 2.51 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* Data Source File
* 1. Fetch data from source.
* 2. Process data.
* 3. Add to cache and return
*/
const NodeCache = require('node-cache');
const axios = require('axios');
const { countryNameMap } = require('./constants');
const myCache = new NodeCache({ stdTTL: 100, checkperiod: 600 });
/**
* John Hopkins Univ. data source API.
* The data needs to be flattened.
* @todo Move the data processing from `view` files to this `data` file.
* @returns {Object} JHUDataObject
*/
exports.getCoronaData = async () => {
const CORONA_ALL_KEY = 'coronaAll';
const cache = myCache.get(CORONA_ALL_KEY);
if (cache) {
console.log('cache', CORONA_ALL_KEY);
return cache;
}
const result = await axios('https://coronavirus-tracker-api.herokuapp.com/all');
if (!result || !result.data) {
throw new Error('Source API failure.');
}
myCache.set(CORONA_ALL_KEY, result.data, 60 * 15);
return result.data;
};
/**
* Fetch Worldometers Data.
* As JHU data updates once a day, this was added.
* This API scrapes data from `https://www.worldometers.info/coronavirus/`
* and updates very frequenly.
* */
exports.getWorldoMetersData = async (countryCode = 'ALL') => {
const key = `worldMetersData_${countryCode}`;
const cache = myCache.get(key);
if (cache) {
console.log('cache', key);
return cache;
}
const result = await axios('https://corona.lmao.ninja/countries?sort=cases');
if (!result || !result.data) {
throw new Error('WorldoMeters Source API failure');
}
const worldStats = result.data.reduce((acc, countryObj) => {
acc.cases += countryObj.cases;
acc.todayCases += countryObj.todayCases;
acc.deaths += countryObj.deaths;
acc.todayDeaths += countryObj.todayDeaths;
acc.recovered += countryObj.recovered;
acc.active += countryObj.active;
acc.critical += countryObj.critical;
return acc;
}, {
country: 'World',
countryCode: 'World',
cases: 0,
todayCases: 0,
deaths: 0,
todayDeaths: 0,
recovered: 0,
active: 0,
critical: 0,
});
result.data.forEach(obj => {
obj.countryCode = countryNameMap[obj.country];
obj.confirmed = obj.cases;
});
worldStats.casesPerOneMillion = (worldStats.cases / 7794).toFixed(2);
worldStats.confirmed = worldStats.cases;
let finalData = result.data;
if (countryCode && countryCode !== 'ALL') {
finalData = finalData.filter(obj => obj.countryCode === countryCode);
}
const returnObj = { data: finalData, worldStats };
myCache.set(key, returnObj, 60 * 15);
return returnObj;
};