Last change
on this file since bdd6491 was e29cc2e, checked in by Ema <ema_spirova@…>, 3 years ago |
primeNG components
|
-
Property mode
set to
100644
|
File size:
1.4 KB
|
Line | |
---|
1 | import { ERROR_PACKET, PACKET_TYPES_REVERSE } from "./commons.js";
|
---|
2 | const decodePacket = (encodedPacket, binaryType) => {
|
---|
3 | if (typeof encodedPacket !== "string") {
|
---|
4 | return {
|
---|
5 | type: "message",
|
---|
6 | data: mapBinary(encodedPacket, binaryType)
|
---|
7 | };
|
---|
8 | }
|
---|
9 | const type = encodedPacket.charAt(0);
|
---|
10 | if (type === "b") {
|
---|
11 | const buffer = Buffer.from(encodedPacket.substring(1), "base64");
|
---|
12 | return {
|
---|
13 | type: "message",
|
---|
14 | data: mapBinary(buffer, binaryType)
|
---|
15 | };
|
---|
16 | }
|
---|
17 | if (!PACKET_TYPES_REVERSE[type]) {
|
---|
18 | return ERROR_PACKET;
|
---|
19 | }
|
---|
20 | return encodedPacket.length > 1
|
---|
21 | ? {
|
---|
22 | type: PACKET_TYPES_REVERSE[type],
|
---|
23 | data: encodedPacket.substring(1)
|
---|
24 | }
|
---|
25 | : {
|
---|
26 | type: PACKET_TYPES_REVERSE[type]
|
---|
27 | };
|
---|
28 | };
|
---|
29 | const mapBinary = (data, binaryType) => {
|
---|
30 | const isBuffer = Buffer.isBuffer(data);
|
---|
31 | switch (binaryType) {
|
---|
32 | case "arraybuffer":
|
---|
33 | return isBuffer ? toArrayBuffer(data) : data;
|
---|
34 | case "nodebuffer":
|
---|
35 | default:
|
---|
36 | return data; // assuming the data is already a Buffer
|
---|
37 | }
|
---|
38 | };
|
---|
39 | const toArrayBuffer = buffer => {
|
---|
40 | const arrayBuffer = new ArrayBuffer(buffer.length);
|
---|
41 | const view = new Uint8Array(arrayBuffer);
|
---|
42 | for (let i = 0; i < buffer.length; i++) {
|
---|
43 | view[i] = buffer[i];
|
---|
44 | }
|
---|
45 | return arrayBuffer;
|
---|
46 | };
|
---|
47 | export default decodePacket;
|
---|
Note:
See
TracBrowser
for help on using the repository browser.