Resolve "Feat(SSE): Add msgpackr parser for SSE Client"

This commit is contained in:
2025-04-07 02:52:23 +00:00
committed by Jim Hamill
parent 8441a19423
commit cec5d128f3
3 changed files with 74 additions and 22 deletions
@@ -0,0 +1,54 @@
import { SSEClient, SSEClientOptions, SSEvent } from './sse-client';
import { unpackMultiple } from 'msgpackr';
/**
* SSEClientMsgpackr is a subclass of SSEClient that uses msgpackr to parse the events.
*/
export class SSEClientMsgpackr extends SSEClient {
/**
* Creates a new SSEClientMsgpackr instance.
* @param {string} url The URL to connect to
* @param {SSEClientOptions} options The options for the SSEClient
* @returns {SSEClientMsgpackr} A new SSEClientMsgpackr instance
*/
public static async from(url: string, options: SSEClientOptions) {
const client = new SSEClientMsgpackr(url, options);
await client.connect();
return client;
}
/**
* Parses the events from the msgpackr message buffer.
* @param {Uint8Array} chunk The chunk to parse
* @returns {SSEvent[]} The parsed events
*/
protected parseEvents(chunk: Uint8Array): SSEvent[] {
// Append new chunk to existing buffer
this.messageBuffer = new Uint8Array([...this.messageBuffer, ...chunk]);
// Create an array to store the parsed events
const events: SSEvent[] = [];
try {
// Try to decode the entire buffer as msgPackr messages
unpackMultiple(this.messageBuffer, (value, start, end) => {
// Remove the event from the buffer
this.messageBuffer = this.messageBuffer.slice(end);
// Add the event to the events array
events.push(value);
});
} catch (error) {
// If we can't decode the buffer, it might be incomplete
// Keep the entire buffer for next time
} finally {
// Update buffer with any remaining unprocessed content
this.messageBuffer = new Uint8Array(this.messageBuffer);
// Return the events
return events;
}
}
}