|
1 | 1 | const express = require('express');
|
2 |
| -const d3_dsv = require('d3-dsv'); |
3 |
| -const util = require('util'); |
4 |
| -const request = require('request'); |
5 |
| - |
6 | 2 | const app = express();
|
7 |
| -const get = util.promisify(request.get); |
| 3 | + |
| 4 | +const casesRoute = require('./routes/cases'); |
8 | 5 |
|
9 | 6 | app.set('port', (process.env.PORT || 5000));
|
10 | 7 |
|
11 | 8 | // route index
|
12 |
| -app.get('/:country*?', (req, res) => { |
13 |
| - // if any parameter (country) was passed |
14 |
| - if (req.params.country) { |
15 |
| - // fetch the data |
16 |
| - get_data() |
17 |
| - .then(response => { |
18 |
| - |
19 |
| - let countryData = {} |
20 |
| - // loop through all the countries |
21 |
| - response.forEach(country => { |
22 |
| - // for every country |
23 |
| - // if there is Country/Region is equal to passed country |
24 |
| - if (country['Country/Region'].toString().toLowerCase() === req.params.country.toLowerCase()) { |
25 |
| - countryData = country |
26 |
| - } |
27 |
| - }) |
28 |
| - // send the country data back |
29 |
| - res.send(countryData); |
30 |
| - }).catch(e => console.log(e)) |
31 |
| - } else { //if no parameter was passed |
32 |
| - // fetch the data |
33 |
| - get_data() |
34 |
| - .then(response => res.json(response)); |
35 |
| - } |
36 |
| -}); |
37 |
| - |
38 |
| -// function that fetches and returns the parsed data |
39 |
| -let get_data = () => { |
40 |
| - let url = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv' |
41 |
| - return get({ url }) |
42 |
| - .then(resp => resp.body) //return the body of the response |
43 |
| - .then(text => { |
44 |
| - let jsonData = d3_dsv.csvParse(text); |
45 |
| - let tempArray = [] |
46 |
| - // loop through the data |
47 |
| - jsonData.forEach(element => { |
48 |
| - // assign the value of last property to a variable |
49 |
| - let total = element[Object.keys(element).pop()] |
50 |
| - // delete the last property |
51 |
| - delete element[Object.keys(element).pop()] |
52 |
| - // assign a new property total to the total value |
53 |
| - element['total'] = total |
54 |
| - // push the new element to the tempArray |
55 |
| - tempArray.push(element) |
56 |
| - }); |
57 |
| - // return the tempArray |
58 |
| - return tempArray; |
59 |
| - }).catch((e) => { |
60 |
| - // on error |
61 |
| - return [{ |
62 |
| - "message": "unable to load the data", |
63 |
| - 'error': e |
64 |
| - }]; |
65 |
| - }) |
66 |
| -} |
| 9 | +app.use('/', casesRoute); |
67 | 10 |
|
68 | 11 | app.listen(app.get('port'), () => {
|
69 | 12 | console.log(`Server started on port ${app.get('port')}`);
|
|
0 commit comments