-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
103 lines (85 loc) · 2.58 KB
/
server.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// dependencies
var express = require('express');
var http = require('http');
const https = require('https');
const request = require('request');
var fs = require('fs');
var ioServer = require('socket.io');
var app = express();
const IS_PRODUCTION = process.env.NODE_ENV == 'production';
const PORT = IS_PRODUCTION ? 80 : 3000;
// start http server
const httpServer = http.createServer(app);
var io = new ioServer();
io.attach(httpServer);
// start https if prod
if (IS_PRODUCTION) {
const privateKey = fs.readFileSync('/etc/letsencrypt/live/covidinc.io/privkey.pem', 'utf8');
const certificate = fs.readFileSync('/etc/letsencrypt/live/covidinc.io/cert.pem', 'utf8');
const ca = fs.readFileSync('/etc/letsencrypt/live/covidinc.io/chain.pem', 'utf8');
const credentials = {
key: privateKey,
cert: certificate,
ca: ca
};
const httpsServer = https.createServer(credentials, app);
io.attach(httpsServer);
app.all('*', httpsRedir);
httpsServer.listen(443, function () {
console.log('HTTPS server running on port 443');
});
}
httpServer.listen(PORT, function () {
console.log('HTTP server running on port ' + PORT);
});
// serve front-end website
app.use(express.static('./client'));
function httpsRedir(req, res, next) {
if(req.secure){
return next();
};
res.redirect('https://' + req.hostname + req.url);
}
function getCases(callback){
request('https://af18f64x36.execute-api.us-east-1.amazonaws.com/prod/coronavirus', (error, response, body) => {
if (!error && response.statusCode == 200) {
var importedJSON = JSON.parse(body);
callback(importedJSON);
}
})
}
function getNews(callback) {
request('https://6ezcou7jl9.execute-api.us-east-1.amazonaws.com/default/news', (error, response, body) => {
if (!error && response.statusCode == 200) {
var importedJSON = JSON.parse(body);
callback(importedJSON);
}
})
}
function readJsonFileSync(filepath, encoding){
if (typeof (encoding) == 'undefined'){
encoding = 'utf8';
}
const file = fs.readFileSync(filepath, encoding);
return JSON.parse(file);
}
function getPorts() {
const filepath = __dirname + '/ports.json';
return readJsonFileSync(filepath);
}
io.on('connection', function(socket){
socket.on('get_cases', function(){
getCases((json) => {
socket.json.emit('load_finish', json);
});
});
socket.on('get_news', function() {
getNews((json) => {
socket.json.emit('news_loaded', json);
});
});
socket.on('get_ports', function(){
const jsonPorts = getPorts();
socket.json.emit('ports_loaded', jsonPorts);
});
});