react-chat-stream icon indicating copy to clipboard operation
react-chat-stream copied to clipboard

Parse Server Response

Open ttessarolo opened this issue 1 year ago • 1 comments

Hi – the decode process works fine only if the server respond with just strings.

But the Server-Sent Events (SSE) standard implies a more complex response:

interface EventMessage {
  /**
   * Message payload
   */
  data?: string;

  /**
   * Message identifier, if set, client will send `Last-Event-ID: <id>` header on reconnect
   */
  id?: string;

  /**
   * Message type
   */
  event?: string;

  /**
   * Update client reconnect interval (how long will client wait before trying to reconnect).
   */
  retry?: number;

  /**
   * Message comment
   */
  comment?: string;
}

Fort that reason I suggest to add an option to let the code not just parse simple text answers but also a SSE compliant response.

Inside the decodeStreamToJson function you could parse the complex response like that:

const decoded = decoder.decode(value);
        const splitted = decoded
          .split("\n")
          .filter((s) => {
            if (s?.startsWith("data:")) return true;
            return false;
          })
          .map((s) => s.replace("data: ", ""));

        if (splitted.length > 0 && splitted[0] !== "Stream closed") {
          yield splitted[0];
        }

Just a suggestion. Thanks for this Hook ;)

ttessarolo avatar Dec 16 '23 09:12 ttessarolo