-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
68 lines (55 loc) · 1.87 KB
/
index.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
// TODO:: Prevent XSS on backend
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/dd', function(err, db){
if(!err){
console.log('connected to db');
}
else{
console.log('no connected to db');
console.log(err);
}
});
function postToDb(data) {
MongoClient.connect('mongodb://localhost/dd', function(err, db) {
if(err)
throw err;
console.log('connected to the db');
db.collection('messages').insertOne(data);
});
}
app.use(express.static('public'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
app.get('/chatroom', function(req, res) {
res.sendFile(__dirname + '/chatroom.html');
})
app.get('/recent', function(req, res) {
res.setHeader('Content-Type', 'application/json');
MongoClient.connect('mongodb://localhost:27017/dd', function(err, db) {
if(err)
throw err;
db.collection('messages').find().sort({createdAt: -1}).limit(20).toArray(function(err, result) {
if(err)
throw err;
res.send(JSON.stringify(result));
});
})
});
io.on('connection', function(socket) {
console.log("new connection");
socket.on('message', function(msgBody) {
if(msgBody.name && msgBody.message) {
msgBody.createdAt = new Date();
postToDb({fromId: msgBody.fromId, name: msgBody.name, message: msgBody.message, createdAt: msgBody.createdAt});
socket.broadcast.emit('message', {fromId: msgBody.fromId, name: msgBody.name, message: msgBody.message, createdAt: msgBody.createdAt});
}
});
});
http.listen(3000, '0.0.0.0', function() {
console.log("listening on 3000");
});