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