socket.io icon indicating copy to clipboard operation
socket.io copied to clipboard

I have seen implementation of custom parser, but there is no clear implementation of it in vanilla javascript

Open shiva-sandupatla opened this issue 3 years ago • 0 comments

Hey,

I have visited https://socket.io/docs/v4/custom-parser/#implementing-your-own-parser

I use the same default parser to just add some extension functionality to it and used the following way on the client side

class Encoder {
  /**
   * Encode a packet into a list of strings/buffers
   */
  encode(packet) {
    return [JSON.stringify(packet)];
  }
}

class Decoder {
  add(chunk) {
    const packet = JSON.parse(chunk);
    if (this.isPacketValid(packet)) {
      this.emit("decoded", packet);
    } else {
      throw new Error("invalid format");
    }
  }
  isPacketValid({ type, data, nsp, id }) {
    const isNamespaceValid = typeof nsp === "string";
    const isAckIdValid = id === undefined || Number.isInteger(id);
    if (!isNamespaceValid || !isAckIdValid) {
      return false;
    }
    switch (type) {
      case 0: // CONNECT
        return data === undefined || typeof data === "object";
      case 1: // DISCONNECT
        return data === undefined;
      case 2: // EVENT
        return Array.isArray(data) && data.length > 0;
      case 3: // ACK
        return Array.isArray(data);
      case 4: // CONNECT_ERROR
        return typeof data === "object";
      default:
        return false;
    }
  }
  destroy() {}
}

const socket = io("http://localhost:8500", {
  auth: {
    token: "token goes here",
  },
  parser: { Encoder, Decoder },
});

it is showing the below error in the console.

image

Am I doing anything wrong, or is my implementation wrong? please guide me through it.

Regards, Shiva

shiva-sandupatla avatar Aug 07 '22 16:08 shiva-sandupatla