-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsocket.js
49 lines (46 loc) · 1.14 KB
/
socket.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
"use strict";
/** @typedef {import("firebase")} firebase */
class Socket {
/**
* @param {firebase.database.Reference} read
* @param {firebase.database.Reference} write
*/
constructor(read, write) {
this.read = read;
this.write = write;
this.callbacks = new Map([["message", []]]);
setTimeout(() => read.on("child_added", ss => this.onMessage(ss)));
}
/**
* @param {firebase.database.DataSnapshot} snapshot
*/
onMessage(snapshot) {
if (snapshot.key === "__CONNECTION") {
// if switch to metadata records, create {kind: connection, data: ...}?
return;
}
const data = snapshot.val();
this.callbacks.get("message").forEach(cb => cb({data}));
}
/**
* @param {any} data of JSON-serializable values
*/
send(data) {
this.write.push().set(data);
}
/**
* @param {'message'} event
* @param {({data: any}) => void} cb
*/
addEventListener(event, cb) {
const arr = this.callbacks.get(event);
if (!arr) {
throw new Error(`Unsupported event type ${event}`);
}
arr.push(cb);
}
close() {
this.read.off("child_added");
}
}
module.exports = Socket;