-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStream.js
More file actions
48 lines (39 loc) · 1.12 KB
/
Stream.js
File metadata and controls
48 lines (39 loc) · 1.12 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
import coreModule from './core.js';
const core = await coreModule.getModule();
function isBlob(message) {
try {
return message instanceof Blob;
} catch (e) {
return false;
}
}
function getArrayFromBlob(blob) {
return blob.arrayBuffer();
}
async function receive(data) {
if (isBlob(data))
data = getArrayFromBlob(data);
return await core.parse(data);
}
export default class Stream {
#data;
#chunkSize;
constructor(data, chunkSize) {
this.#data = data;
this.#chunkSize = chunkSize;
}
send(channel, mode = 'json') {
return core.send({ channel, message: this.#data, mode, chunkSize: this.#chunkSize });
}
get chunkSize() { return this.#chunkSize; }
get data() { return this.#data; }
static from(channel) {
const stream = new Stream(null, channel.maxMessageSize);
channel.onmessage = async function (event) {
const data = event.data;
const message = await receive(data);
stream.onmessage(message);
};
return stream;
}
};