diff --git a/src/index.ts b/src/index.ts index 1b17da5..bd2f719 100644 --- a/src/index.ts +++ b/src/index.ts @@ -9,7 +9,7 @@ type Streamable = | Response | null -interface StreamOption { +type StreamOption = { /** * A string identifying the type of event described. * @@ -31,6 +31,25 @@ interface StreamOption { * attempting to reconnect. */ retry?: number + /** + * The format of the data sent through the stream. + * + * If set to true, the data will be directly sent without + * any transformation. + * + * By default all the data are sent with an id. + */ + rawData?: false +} | { + /** + * The format of the data sent through the stream. + * + * If set to true, the data will be directly sent without + * any transformation. + * + * By default all the data are sent with an id. + */ + rawData: true } const encoder = new TextEncoder() @@ -58,6 +77,7 @@ export class Stream { private _retry?: number private _event?: string + private _rawData?: boolean private label: string = '' private labelUint8Array = new Uint8Array() @@ -98,11 +118,16 @@ export class Stream { constructor( callback?: ((stream: Stream) => void) | MaybePromise, - { retry, event }: StreamOption = {} + streamOption: StreamOption = {} ) { - if (retry) this._retry = retry - if (event) this._event = event - if (retry || event) this.composeLabel() + if (!streamOption.rawData && streamOption.retry) + this._retry = streamOption.retry + if (!streamOption.rawData && streamOption.event) + this._event = streamOption.event + if (streamOption.rawData) + this._rawData = streamOption.rawData + if (!streamOption.rawData && (streamOption.retry || streamOption.event)) + this.composeLabel() switch (typeof callback) { case 'function': @@ -174,6 +199,10 @@ export class Stream { ? Stream.concatUintArray(this.labelUint8Array, data) : data ) + } else if (this._rawData) { + this.controller.enqueue( + encoder.encode(typeof data === 'object' ? JSON.stringify(data) : data.toString()) + ) } else this.controller.enqueue( encoder.encode(