1 | const { PACKET_TYPES } = require("./commons");
|
---|
2 |
|
---|
3 | const withNativeBlob =
|
---|
4 | typeof Blob === "function" ||
|
---|
5 | (typeof Blob !== "undefined" &&
|
---|
6 | Object.prototype.toString.call(Blob) === "[object BlobConstructor]");
|
---|
7 | const withNativeArrayBuffer = typeof ArrayBuffer === "function";
|
---|
8 |
|
---|
9 | // ArrayBuffer.isView method is not defined in IE10
|
---|
10 | const isView = obj => {
|
---|
11 | return typeof ArrayBuffer.isView === "function"
|
---|
12 | ? ArrayBuffer.isView(obj)
|
---|
13 | : obj && obj.buffer instanceof ArrayBuffer;
|
---|
14 | };
|
---|
15 |
|
---|
16 | const encodePacket = ({ type, data }, supportsBinary, callback) => {
|
---|
17 | if (withNativeBlob && data instanceof Blob) {
|
---|
18 | if (supportsBinary) {
|
---|
19 | return callback(data);
|
---|
20 | } else {
|
---|
21 | return encodeBlobAsBase64(data, callback);
|
---|
22 | }
|
---|
23 | } else if (
|
---|
24 | withNativeArrayBuffer &&
|
---|
25 | (data instanceof ArrayBuffer || isView(data))
|
---|
26 | ) {
|
---|
27 | if (supportsBinary) {
|
---|
28 | return callback(data);
|
---|
29 | } else {
|
---|
30 | return encodeBlobAsBase64(new Blob([data]), callback);
|
---|
31 | }
|
---|
32 | }
|
---|
33 | // plain string
|
---|
34 | return callback(PACKET_TYPES[type] + (data || ""));
|
---|
35 | };
|
---|
36 |
|
---|
37 | const encodeBlobAsBase64 = (data, callback) => {
|
---|
38 | const fileReader = new FileReader();
|
---|
39 | fileReader.onload = function() {
|
---|
40 | const content = fileReader.result.split(",")[1];
|
---|
41 | callback("b" + content);
|
---|
42 | };
|
---|
43 | return fileReader.readAsDataURL(data);
|
---|
44 | };
|
---|
45 |
|
---|
46 | module.exports = encodePacket;
|
---|