-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser.js
81 lines (54 loc) · 1.31 KB
/
user.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
'use strict';
let userids = new Set();
class WebSocketUser {
constructor(client) {
// Generate a new uniqid for the user
this._id = WebSocketUser.uniqid;
// Store the ws object as client
this._client = client;
// The user is immediately not joined a room
// We add the user to a room later
this._room = null;
}
get id() {
return this._id;
}
set room(room) {
this._room = room;
}
get room() {
return this._room;
}
static get uniqid() {
// Generate a random number and convert to Base36
let v = (Math.random() * 1e18).toString(36);
// Check if the value is already generated
if (userids.has(v)) {
// If the value already exists
// generate a new one
let c = WebSocketUser.uniqid;
// Store the new value
userids.add(c);
// return the new value
return c;
} else {
// Store the value and return it
userids.add(v);
return v;
}
}
send(msg) {
// Send the message
this._client.send(JSON.stringify(msg));
}
on(event, callback) {
// Attach and propagate valid events only
if (['open', 'close', 'message'].includes(event)) {
this._client.on(event, callback);
}
}
close() {
this._client.close();
}
}
module.exports = WebSocketUser;