forked from bradtraversy/mongochat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
82 lines (71 loc) · 2.43 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
const mongo = require('mongodb').MongoClient;
const client = require('socket.io').listen(4000).sockets;
// Connect to mongo
mongo.connect('mongodb://localhost:27017/meanauth', function(err, db){
if(err){
throw err;
}
console.log('MongoDB connected...');
// Connect to Socket.io
client.on('connection', function(socket){
console.log(socket.handshake.address)
let chat = db.collection('chats');
// Create function to send status
sendStatus = function(s){
socket.emit('status', s);
}
// Get chats from mongo collection
chat.find().limit(100).sort({_id:1}).toArray(function(err, res){
if(err){
throw err;
}
// Emit the messages
// console.log(res);
client.emit('updatedMessages', res);
});
var updateMessages = function(){
// Get chats from mongo collection
chat.find().limit(100).sort({_id:1}).toArray(function(err, res){
if(err){
throw err;
}
// Emit the messages
console.log(res);
client.emit('updatedMessages', res);
});
}
// Handle input events
socket.on('input', function(data){
//console.log(data);
// console.log(data.username);
let name = data.username;
let message = data.message;
//console.log("hello");
//console.log(name+message);
// Check for name and message
if(name == '' || message == ''){
// Send error status
sendStatus('Please enter a name and message');
} else {
// Insert message
chat.insert({username: name, message: message}, function(){
client.emit('updatedMessages', [data]);
// Send status object
sendStatus({
message: 'Message sent',
clear: true
});
});
}
//updateMessages();
});
// Handle clear
socket.on('clear', function(data){
// Remove all chats from collection
chat.remove({}, function(){
// Emit cleared
socket.emit('cleared');
});
});
});
});