-
Notifications
You must be signed in to change notification settings - Fork 0
/
io.js
42 lines (32 loc) · 977 Bytes
/
io.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
var io = require('socket.io')();
var Chat = require('./models/chat');
var User = require('./models/user');
// Can't init messages here as db.get() is still null when first required.
var messages = [];
io.on('connection', function(socket) {
socket.on('loadChats', function() {
var cursor = Chat.findAll();
cursor.toArray(function(err, result) {
if (err) {
throw err;
} else {
socket.emit('loadChatsRet', result);
}
});
});
socket.on('sendMessage', function(user, text) {
let date = new Date();
const c = {
user: user,
time: date.getTime(),
message: text
};
io.emit('messageSent', c);
messages.push(c);
Chat.create(c.user, c.time, c.message);
});
socket.on('newUser', function( newUserData ) {
io.emit('newUserInput', newUserData);
});
});
module.exports = io;