-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
84 lines (72 loc) · 2.29 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
82
83
84
const express = require('express'),
app = express(),
router = express.Router(),
server = require('http').createServer(app),
io = require('socket.io')(server),
MongoClient = require('mongodb').MongoClient,
mongoUrl = 'mongodb://admin:[email protected]:27335/mymongdb',
mongoName = 'mymongdb';
// Static Routes
// ===========================================================
app.use(express.static('public'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
app.get('/stressed', function(req, res){
res.sendFile(__dirname + '/public/stressed.html');
});
app.get('/encouraged', function(req, res){
res.sendFile(__dirname + '/public/encouraged.html');
});
// Database
// ===========================================================
// Mongo Connection Functions
let storeData = function(c, data){
MongoClient.connect(mongoUrl, function(err, client){
client.db(mongoName).collection(c).insertOne({data}, function(err, res){
console.log(JSON.stringify(res));
client.close();
});
});
}
let getData = function(c, limit, callback){
MongoClient.connect(mongoUrl, function(err, client){
client.db(mongoName).collection(c).find({}).limit(limit).toArray(function(err, res){
res.forEach((i)=> callback(i));
client.close();
});
});
}
// Socket
// ===========================================================
io.on('connection', function(socket){
console.log('connected');
let communications = ['stress-word', 'stress-encourage', 'grateful-word'];
// add listeners for each communication type
// each time an even is emitted, store it
// and broadcast it
for(let c of communications){
socket.on(c, function(data){
console.log('heard ', c, ' of ', data);
storeData(c, data);
io.emit(c, data);
});
}
// emit past data on initial connection
// for each communication type, get db data
// and emit results (one by one)
socket.on('join', function(){
console.log('joined...');
for(let c of communications){
let callback = function(item){ io.emit(c, item) };
getData(c, 12, callback);
// getData(c, 8).forEach((item)=> client.emit(c, item));
}
});
});
// Listener
// ===========================================================
const PORT = process.env.PORT || 3000;
server.listen(PORT, function(){
console.log('listening on 3000');
});