-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChatUser.js
75 lines (58 loc) · 1.74 KB
/
ChatUser.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
/** Functionality related to chatting. */
// Room is an abstraction of a chat channel
const Room = require('./Room');
/** ChatUser is a individual connection from client -> server to chat. */
class ChatUser {
/** make chat: store connection-device, rooom */
constructor(send, roomName) {
this._send = send; // "send" function for this user
this.room = Room.get(roomName); // room user will be in
this.name = null; // becomes the username of the visitor
console.log(`created chat in ${this.room.name}`);
}
/** send msgs to this client using underlying connection-send-function */
send(data) {
try {
this._send(data);
} catch {
// If trying to send to a user fails, ignore it
}
}
/** handle joining: add to room members, announce join */
handleJoin(name) {
this.name = name;
this.room.join(this);
this.room.broadcast({
type: 'note',
text: `${this.name} joined "${this.room.name}".`
});
}
/** handle a chat: broadcast to room. */
handleChat(text) {
this.room.broadcast({
name: this.name,
type: 'chat',
text: text
});
}
/** Handle messages from client:
*
* - {type: "join", name: username} : join
* - {type: "chat", text: msg } : chat
*/
handleMessage(jsonData) {
let msg = JSON.parse(jsonData);
if (msg.type === 'join') this.handleJoin(msg.name);
else if (msg.type === 'chat') this.handleChat(msg.text);
else throw new Error(`bad message: ${msg.type}`);
}
/** Connection was closed: leave room, announce exit to others */
handleClose() {
this.room.leave(this);
this.room.broadcast({
type: 'note',
text: `${this.name} left ${this.room.name}.`
});
}
}
module.exports = ChatUser;