-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.js
81 lines (65 loc) · 2.58 KB
/
App.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
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
var port = process.env.PORT || 3000,
express = require("express"),
request = require("request"),
async = require("async"),
app = express();
app.set("view engine", "ejs");
// Declaring path to API
var url = "https://oslobysykkel.no/api/v1/stations";
// API Identifier
// In the following code a enviroment variable has been used to store the API identifier. You can also comment this line, and un-comment the next line and enter the key identifier directly.
var identifier = process.env.identifierOsloBysykkel
//var identifier = "enterkeyhere";
// Defining API's to poll
var stations = {
url: url,
headers: {
'Client-Identifier': identifier
}
};
var availability = {
url: url + "/availability",
headers: {
'Client-Identifier': identifier
}
};
// GET route
app.get("/", function(req, res) {
function callback(error, response, body, cb) {
if(error || response.statusCode != 200)
return cb(true);
cb(null, JSON.parse(body).stations);//instead of sending data directly to view, send it to async callback to merge it latter
}
var tasks = { // tasks to run in parallel
stations: function (cb) {
request(stations, function (error, response, body) {
callback(error, response, body, cb);
});
},
availability: function (cb) {
request(availability, function (error, response, body) {
callback(error, response, body, cb);
});
}
};
async.parallel(tasks, function (err, resp) {
if(err) {
console.log(err);
return;
}
var availabilityIdMap = resp.availability.map(function (availability) { return availability.id; });//get an array of all the availability ids
var data = resp.stations.map(function (station) { //merging station to corresponding availability object
var availabilityIndex = availabilityIdMap.indexOf(station.id); // finding the availability against the station id.
if(availabilityIndex < 0) //availability not found, just return station
return station;
var matchingAvailabilityObj = resp.availability[availabilityIndex]; //get the matching availability object
var mergedObj = Object.assign(station, matchingAvailabilityObj); //merge both objects
return mergedObj;
});
// now the data will have an array of merged object with properties from station and availability objects
res.render("index", {data: data});
});
});
app.listen(port, function(){
console.log("App started and listening on port " + port + "!");
});