forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprotocol.ts
More file actions
47 lines (38 loc) · 1.15 KB
/
protocol.ts
File metadata and controls
47 lines (38 loc) · 1.15 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
import * as uuid from 'uuid';
export default class Protocol {
id = uuid.v4();
messageId = 0;
worker: Worker;
constructor(worker: Worker, listenObject /* listen object with funcs on handling */) {
this.worker = worker;
window.addEventListener('message', () => {});
}
send(name, message: any): Promise<any> {
return new Promise((resolve, reject) => {
const messageId: string = this.id + this.messageId++;
const listenerFunction: any = (m: MessageEvent) => {
const { data } = m;
if (data.ev !== 'protocol') {
return;
}
if (data.messageId === messageId) {
if (data.error) {
const err = new Error(data.error.title);
err.message = data.error.message;
reject(err);
} else {
resolve(data.data);
}
this.worker.removeEventListener('message', listenerFunction);
}
};
this.worker.addEventListener('message', listenerFunction);
const messageToSend = {
ev: 'protocol',
data: message,
messageId,
};
this.worker.postMessage(messageToSend);
});
}
}