Skip to content

Commit 7a7a26c

Browse files
separated the get data function
1 parent ff39f8b commit 7a7a26c

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

helpers/fetch-data.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
const d3_dsv = require('d3-dsv');
2+
const util = require('util');
3+
const request = require('request');
4+
5+
const get = util.promisify(request.get);
6+
7+
// function that fetches and returns the parsed data
8+
let get_data = (url) => {
9+
return get({ url })
10+
.then(resp => resp.body) //return the body of the response
11+
.then(text => {
12+
let jsonData = d3_dsv.csvParse(text);
13+
let tempArray = []
14+
// loop through the data
15+
jsonData.forEach(element => {
16+
// assign the value of last property to a variable
17+
let total = element[Object.keys(element).pop()]
18+
// delete the last property
19+
delete element[Object.keys(element).pop()]
20+
// assign a new property total to the total value
21+
element['total'] = total
22+
// push the new element to the tempArray
23+
tempArray.push(element)
24+
});
25+
// return the tempArray
26+
return tempArray;
27+
}).catch((e) => {
28+
// on error
29+
return [{
30+
"message": "unable to load the data",
31+
'error': e
32+
}];
33+
})
34+
}
35+
36+
module.exports = get_data;

0 commit comments

Comments
 (0)