0
0
mirror of https://github.com/honojs/hono.git synced 2024-11-29 09:43:20 +01:00
hono/deno_dist/utils/stream.ts
Sor4chi 31f0605209 feat: Add c.stream() (#1437)
* feat: implement stream api utility-class

* test: write the test of StreamApi

* feat: implement `c.stream` to context

* test: write the test of `c.stream()`

* chore: denoify

* fix: extend for bytes, remove buffer system, add pipe and log interface

* test: update test about log, pipe, etc... for streaming API

* feat: extend textStream interface, remove utf-8 content-type

* test: add test about `c.textStream`

* refactor: update some args name

* chore: denoify

* fix: for deno, removed the optional parameter of `write` and `writeln`

* chore: denoify

* feat: add charset for textStream content-type header

* fix: rename textStream to streamText

* fix: reuse stream in streamText for bundle size

* feat: add `stream.wait()` api

* chore: denoify

* fix: rename `stream.wait` to `stream.sleep`

* test: use `stream.sleep` for waiting

* refactor: remove `stream.log`

* fix: remove preHeader from `c.stream()` and use `transfer-encoding` only `c.streamText()`

* chore: denoify

* refactoring: remove preHeader initialize

* test: reduce sleep duration

* chore: denoify

Co-authored-by: Glen Maddern <glenmaddern@gmail.com>
2023-09-17 00:57:26 +09:00

39 lines
889 B
TypeScript

export class StreamingApi {
private writer: WritableStreamDefaultWriter<Uint8Array>
private encoder: TextEncoder
private writable: WritableStream
constructor(writable: WritableStream) {
this.writable = writable
this.writer = writable.getWriter()
this.encoder = new TextEncoder()
}
async write(input: Uint8Array | string) {
if (typeof input === 'string') {
input = this.encoder.encode(input)
}
await this.writer.write(input)
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() {
await this.writer.close()
}
async pipe(body: ReadableStream) {
this.writer.releaseLock()
await body.pipeTo(this.writable, { preventClose: true })
this.writer = this.writable.getWriter()
}
}