-
Notifications
You must be signed in to change notification settings - Fork 2
/
firesocket.js
78 lines (69 loc) · 1.73 KB
/
firesocket.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
"use strict";
/** @typedef {import("firebase")} firebase */
const Socket = require("./socket");
class FireSocket {
/**
* @param {string} uid
* @param {firebase} firebase
*/
constructor(uid, firebase) {
this.database = firebase.database();
this.callbacks = new Map([
// events not in common with socket
["open", []],
]);
this.readyState = FireSocket.CONNECTING;
const write = this.database.ref(`user/${uid}`);
write.update({"__CONNECTION": true}, () => this.onOpen());
const read = this.database.ref(`server/${uid}`);
this.socket = new Socket(/** @type {any} */ (read), /** @type {any} */ (write));
}
onOpen() {
this.readyState = FireSocket.OPEN;
this.callbacks.get("open").forEach(cb => cb());
}
get CONNECTING() {
return FireSocket.CONNECTING;
}
get CLOSING() {
return FireSocket.CLOSING;
}
get CLOSED() {
return FireSocket.CLOSED;
}
get OPEN() {
return FireSocket.OPEN;
}
/**
* @callback onEvent
* @param {{ data?: any }} cb
*/
/**
* @param {'open' | 'close' | 'message'} event
* @param {onEvent} cb
*/
addEventListener(event, cb) {
// TODO(close) actually fire the close event and set the readyState
const arr = this.callbacks.get(event);
if (arr) {
arr.push(cb);
} else {
this.socket.addEventListener(/** @type {any} **/ (event), cb);
}
}
/**
* @param {any} data of JSON-serializable values
* @param {undefined} [options] unsupported
*/
send(data, options) {
if (options) {
throw Error("options unsupported");
}
this.socket.send(data);
}
}
FireSocket.CONNECTING = 0;
FireSocket.OPEN = 1;
FireSocket.CLOSING = 2;
FireSocket.CLOSED = 3;
module.exports = FireSocket;