-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.ts
More file actions
171 lines (142 loc) · 4.38 KB
/
Copy pathapi.ts
File metadata and controls
171 lines (142 loc) · 4.38 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
export class WSBackend {
private ws: WebSocket | null = null;
private tokenProvider?: () => string;
private url: string;
private callbacks: Record<string, {
callback: (err: any, res: any) => void;
timeout: ReturnType<typeof setTimeout>;
}> = {};
private broadcastListeners: Map<string, Set<(data: any) => void>> = new Map();
private counter = 0;
private _api: any = null;
private queue: Array<{ id: string; method: string; params: any[]; resolve: Function; reject: Function }> = [];
private reconnectDelay = 1000;
private _connected = false;
private connectedListeners: Array<() => void> = [];
private disconnectedListeners: Array<() => void> = [];
private callTimeout = 10000;
constructor(url: string) {
this.url = url;
this._api = new Proxy({}, {
get: (_t, method: string) => (...args: any[]) => this.call(method, args)
});
this.connect();
}
public setTokenProvider(fn: () => string) {
this.tokenProvider = fn;
}
public get api() {
return this._api;
}
public get connected() {
return this._connected;
}
public onConnected(cb: () => void) {
this.connectedListeners.push(cb);
}
public onDisconnected(cb: () => void) {
this.disconnectedListeners.push(cb);
}
public setCallTimeout(ms: number) {
this.callTimeout = ms;
}
public subscribe<K extends keyof BroadcastEvents>(topic: K, callback: (data: BroadcastEvents[K]) => void): () => void {
const topicStr = String(topic);
if (!this.broadcastListeners.has(topicStr)) {
this.broadcastListeners.set(topicStr, new Set());
}
const cb = callback as (data: any) => void;
this.broadcastListeners.get(topicStr)!.add(cb);
return () => {
this.broadcastListeners.get(topicStr)?.delete(cb);
};
}
private connect() {
this.ws = new WebSocket(this.url);
this.ws.onopen = () => {
console.log("[WS] Connected to", this.url);
this._connected = true;
this.connectedListeners.forEach(cb => cb());
this.queue.forEach(item => {
this._send(item.id, item.method, item.params);
});
this.queue = [];
};
this.ws.onmessage = (evt) => {
let msg: any;
try {
msg = JSON.parse(evt.data);
} catch {
return;
}
if (msg.topic) {
const listeners = this.broadcastListeners.get(msg.topic);
if (listeners) {
listeners.forEach(cb => cb(msg.data));
}
return;
}
const callbackData = this.callbacks[msg.id];
if (!callbackData) return;
clearTimeout(callbackData.timeout);
if (msg.result && typeof msg.result === "object" && ("data" in msg.result || "error" in msg.result)) {
const r = msg.result;
callbackData.callback(r.error, r.data);
} else {
callbackData.callback(msg.error, msg.result);
}
delete this.callbacks[msg.id];
};
this.ws.onclose = () => {
const wasConnected = this._connected;
this._connected = false;
Object.keys(this.callbacks).forEach(id => {
const callbackData = this.callbacks[id];
if (callbackData) {
clearTimeout(callbackData.timeout);
callbackData.callback({ message: 'WebSocket disconnected' }, null);
delete this.callbacks[id];
}
});
if (wasConnected) {
this.disconnectedListeners.forEach(cb => cb());
}
console.log("[WS] Disconnected. Reconnecting...");
setTimeout(() => this.connect(), this.reconnectDelay);
};
this.ws.onerror = (e) => {
console.warn("[WS] Error:", e);
this.ws?.close();
};
}
private call(method: string, params: any[]): Promise<any> {
const id = (++this.counter).toString();
return new Promise((resolve) => {
const timeout = setTimeout(() => {
if (this.callbacks[id]) {
console.warn(`[WS] Call timeout for ${method} (id: ${id})`);
this.callbacks[id].callback({ message: 'Request timeout' }, null);
delete this.callbacks[id];
}
}, this.callTimeout);
this.callbacks[id] = {
callback: (err, res) => {
resolve({ data: res, error: err });
},
timeout
};
if (this._connected && this.ws && this.ws.readyState === WebSocket.OPEN) {
this._send(id, method, params);
} else {
console.log("[WS] Queueing call", method, id, params);
this.queue.push({ id, method, params, resolve, reject: () => { } });
}
});
}
private _send(id: string, method: string, params: any[]) {
if (!this.ws) throw new Error("WebSocket not initialized");
const msg: any = { id, method, params };
if (this.tokenProvider) msg.token = this.tokenProvider();
this.ws.send(JSON.stringify(msg));
}
}