2023-09-16 16:28:57 +02:00
|
|
|
export class StreamingApi {
|
|
|
|
private writer: WritableStreamDefaultWriter<Uint8Array>
|
|
|
|
private encoder: TextEncoder
|
|
|
|
private writable: WritableStream
|
2024-01-02 15:18:04 +01:00
|
|
|
private abortSubscribers: (() => void | Promise<void>)[] = []
|
|
|
|
responseReadable: ReadableStream
|
2023-09-16 16:28:57 +02:00
|
|
|
|
2024-01-02 15:18:04 +01:00
|
|
|
constructor(writable: WritableStream, _readable: ReadableStream) {
|
2023-09-16 16:28:57 +02:00
|
|
|
this.writable = writable
|
|
|
|
this.writer = writable.getWriter()
|
|
|
|
this.encoder = new TextEncoder()
|
2024-01-02 15:18:04 +01:00
|
|
|
|
|
|
|
const reader = _readable.getReader()
|
|
|
|
|
|
|
|
this.responseReadable = new ReadableStream({
|
|
|
|
async pull(controller) {
|
|
|
|
const { done, value } = await reader.read()
|
2024-01-23 09:12:02 +01:00
|
|
|
done ? controller.close() : controller.enqueue(value)
|
2024-01-02 15:18:04 +01:00
|
|
|
},
|
|
|
|
cancel: () => {
|
|
|
|
this.abortSubscribers.forEach((subscriber) => subscriber())
|
|
|
|
},
|
|
|
|
})
|
2023-09-16 16:28:57 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
async write(input: Uint8Array | string) {
|
2023-09-20 15:53:30 +02:00
|
|
|
try {
|
|
|
|
if (typeof input === 'string') {
|
|
|
|
input = this.encoder.encode(input)
|
|
|
|
}
|
|
|
|
await this.writer.write(input)
|
|
|
|
} catch (e) {
|
|
|
|
// Do nothing. If you want to handle errors, create a stream by yourself.
|
2023-09-16 16:28:57 +02:00
|
|
|
}
|
|
|
|
return this
|
|
|
|
}
|
|
|
|
|
|
|
|
async writeln(input: string) {
|
|
|
|
await this.write(input + '\n')
|
|
|
|
return this
|
|
|
|
}
|
|
|
|
|
|
|
|
sleep(ms: number) {
|
|
|
|
return new Promise((res) => setTimeout(res, ms))
|
|
|
|
}
|
|
|
|
|
|
|
|
async close() {
|
2023-09-20 15:53:30 +02:00
|
|
|
try {
|
|
|
|
await this.writer.close()
|
|
|
|
} catch (e) {
|
|
|
|
// Do nothing. If you want to handle errors, create a stream by yourself.
|
|
|
|
}
|
2023-09-16 16:28:57 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
async pipe(body: ReadableStream) {
|
|
|
|
this.writer.releaseLock()
|
|
|
|
await body.pipeTo(this.writable, { preventClose: true })
|
|
|
|
this.writer = this.writable.getWriter()
|
|
|
|
}
|
2024-01-02 15:18:04 +01:00
|
|
|
|
|
|
|
async onAbort(listener: () => void | Promise<void>) {
|
|
|
|
this.abortSubscribers.push(listener)
|
|
|
|
}
|
2023-09-16 16:28:57 +02:00
|
|
|
}
|