-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
46 lines (40 loc) · 1.69 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
let Promise = require("bluebird");
let express = require('express');
let morgan = require('morgan');
let cheerio = require('cheerio');
let request = Promise.promisifyAll(require('request'));
let app = express();
let currentPollResults = {hillary: 0, trump: 0};
let getPollData = function (pageBody) {
let $ = cheerio.load(pageBody);
let hillary = new Number($('#container > div.alpha-container > div > div.chart_wrapper > div.chart_header > table > tbody > tr:nth-child(1) > td > div.value > span').text());
let trump = new Number($('#container > div.alpha-container > div > div.chart_wrapper > div.chart_header > table > tbody > tr:nth-child(2) > td > div.value > span').text());
return {hillary, trump};
};
let updatePollData = function() {
console.log("Retrieving poll data");
request.getAsync('http://www.realclearpolitics.com/epolls/2016/president/us/general_election_trump_vs_clinton-5491.html')
.then((page) => {
currentPollResults = getPollData(page.body)
console.log("Current Poll Results = " + JSON.stringify(currentPollResults));
})
.catch((err) => {
console.log("Error retrieving web page!");
console.log("Status Code: " + err.statusCode);
console.log("Message: " + err.message);
})
.finally(() => {
setTimeout(updatePollData, 1000 * 60 * 30);
});
};
app.use(morgan('combined'));
app.get('/', (req, res) => {
res.send("US Presidential Election 2016 Poll Data");
});
app.get('/poll/latest', (req, res) => {
res.send(currentPollResults);
});
app.listen(3000, () => {
console.log('ElectionPoll service listening on port 3000!');
updatePollData();
});