decodePacket.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. const { PACKET_TYPES_REVERSE, ERROR_PACKET } = require("./commons");
  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. module.exports = decodePacket;