Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Send raw data through the stream #9

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 34 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ type Streamable =
| Response
| null

interface StreamOption {
type StreamOption = {
/**
* A string identifying the type of event described.
*
Expand All @@ -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()
Expand Down Expand Up @@ -58,6 +77,7 @@ export class Stream<Data extends string | number | boolean | object> {

private _retry?: number
private _event?: string
private _rawData?: boolean
private label: string = ''
private labelUint8Array = new Uint8Array()

Expand Down Expand Up @@ -98,11 +118,16 @@ export class Stream<Data extends string | number | boolean | object> {

constructor(
callback?: ((stream: Stream<Data>) => void) | MaybePromise<Streamable>,
{ 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':
Expand Down Expand Up @@ -174,6 +199,10 @@ export class Stream<Data extends string | number | boolean | object> {
? 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(
Expand Down