forked from sagarkarira/coronavirus-tracker-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
84 lines (65 loc) · 2.46 KB
/
app.js
File metadata and controls
84 lines (65 loc) · 2.46 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
const express = require('express');
const app = express();
const lookup = require('country-code-lookup');
const morgan = require('morgan');
const port = process.env.PORT || 3001;
const { getCountryTable, getJSONData, getJSONDataForCountry } = require('./lib/byCountry');
const { getCompleteTable } = require('./lib/corona');
const { countryUpperCase, lookupCountry } = require('./lib/helpers');
function errorHandler(error, res) {
console.error(error);
return res.send('I am sorry. Something went wrong. Please report it');
}
app.use(morgan(':remote-addr :remote-user :method :url :status :res[content-length] - :response-time ms'));
app.get('/', (req, res) => {
const format = req.query.format ? req.query.format : '';
if (format.toLowerCase() === 'json') {
return getJSONData().then(result => {
res.setHeader('Cache-Control', 's-maxage=900');
return res.json(result);
}).catch(error => errorHandler(error, res));
}
return getCompleteTable().then(result => {
res.setHeader('Cache-Control', 's-maxage=900');
return res.send(result);
}).catch(error => errorHandler(error, res));
});
app.get('/:country', (req, res) => {
const { country } = req.params;
const format = req.query.format ? req.query.format : '';
if (!country || 'ALL' === country.toUpperCase()) {
if (format.toLowerCase() === 'json') {
return getJSONData().then(result => {
res.setHeader('Cache-Control', 's-maxage=900');
return res.json(result);
}).catch(error => errorHandler(error, res));
}
return getCompleteTable().then(result => {
res.setHeader('Cache-Control', 's-maxage=900');
return res.send(result);
}).catch(error => errorHandler(error, res));
}
let lookupObj = lookupCountry(country);
if (!lookupObj) {
return res.send(`
Country not found.
Try full country name or country code.
Ex:
- /UK: for United Kingdom
- /US: for United States of America.
- /India: for India.
`);
}
const { iso2 } = lookupObj;
if (format.toLowerCase() === 'json') {
return getJSONDataForCountry(iso2).then(result => {
res.setHeader('Cache-Control', 's-maxage=900');
return res.json(result);
}).catch(error => errorHandler(error, res));
}
return getCountryTable(iso2).then(result => {
res.setHeader('Cache-Control', 's-maxage=900');
return res.send(result);
}).catch(error => errorHandler(error, res));
});
app.listen(port, () => console.log(`Running on ${port}`));