forked from frappe/builder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrealtimeHandler.ts
More file actions
63 lines (55 loc) · 1.47 KB
/
realtimeHandler.ts
File metadata and controls
63 lines (55 loc) · 1.47 KB
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
import { Socket } from "socket.io-client";
import { getCurrentInstance } from "vue";
export default class RealTimeHandler {
open_docs: Set<string>;
socket: Socket;
subscribing: boolean;
constructor() {
this.open_docs = new Set();
this.socket = getCurrentInstance()!.appContext.config.globalProperties.$socket;
this.subscribing = false;
}
on(event: string, callback: (...args: any[]) => void) {
if (this.socket) {
this.socket.on(event, callback);
}
}
off(event: string, callback: (...args: any[]) => void) {
if (this.socket) {
this.socket.off(event, callback);
}
}
emit(event: string, ...args: any[]) {
this.socket.emit(event, ...args);
}
doc_subscribe(doctype: string, docname: string) {
if (this.subscribing) {
return;
}
if (this.open_docs.has(`${doctype}:${docname}`)) {
return;
}
this.subscribing = true;
// throttle to 1 per sec
setTimeout(() => {
this.subscribing = false;
}, 1000);
this.emit("doc_subscribe", doctype, docname);
this.open_docs.add(`${doctype}:${docname}`);
}
doc_unsubscribe(doctype: string, docname: string) {
this.emit("doc_unsubscribe", doctype, docname);
return this.open_docs.delete(`${doctype}:${docname}`);
}
doc_open(doctype: string, docname: string) {
this.emit("doc_open", doctype, docname);
}
doc_close(doctype: string, docname: string) {
this.emit("doc_close", doctype, docname);
}
publish(event: string, message: any) {
if (this.socket) {
this.emit(event, message);
}
}
}