-
Notifications
You must be signed in to change notification settings - Fork 49
/
app.js
73 lines (62 loc) · 1.87 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
const axios = require('axios');
const express= require('express');
const http = require('http');
const morgan = require('morgan');
const port = process.env.PORT || 3000;
const app = express();
const server = http.createServer(app);
let votesAPI = axios.create({
baseURL: process.env.VOTES_API_URI || 'http://votes:3000/'
});
let reportsAPI = axios.create({
baseURL: process.env.REPORTS_API_URI || 'http://reports:3000/'
});
// install route logging middleware
app.use(morgan('dev'));
// install json body parsing middleware
app.use(express.json());
// root route handler
app.get('/', (req, res) => {
return res.send({ success: true, result: 'hello'});
});
// vote route handler
app.post('/vote', async (req, res) => {
try {
console.log('POST /vote: %j', req.body);
let v = { vote: req.body.vote };
let result = await votesAPI.post('/vote', v);
// just pass result data through for now
console.log('posted vote: %j', result.data);
res.send(result.data);
} catch (err) {
console.log('ERROR: POST /vote: %s', err.message || err.response || err);
res.status(500).send({ success: false, reason: 'internal error' });
}
});
// results route handler
app.get('/results', async (req, res) => {
try {
console.log('GET /results');
let result = await reportsAPI.get('/results');
console.log('resp: %j', result.data);
// just passing response through for now
res.send(result.data);
} catch (err) {
console.log('ERROR: POST /results: %s', err.message || err.response || err);
res.status(500).send({ success: false, reason: 'internal error' });
}
});
// initialize and start running
(async () => {
try {
await new Promise(resolve => {
server.listen(port, () => {
console.log(`listening on port ${port}`);
resolve();
});
});
} catch (err) {
console.log(err);
process.exit(1);
}
})();