feat(http): asReadableStream — AsyncIterable to web ReadableStream
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
2 files changed
+53
No files matched your search
@@ -0,0 +1,28 @@
|
|||||||
|
import type { StreamEncoder } from '../encoders';
|
||||||
|
|
||||||
|
/** Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream cancel. */
|
||||||
|
export function asReadableStream(source: AsyncIterable<unknown>, encoder: StreamEncoder): ReadableStream<Uint8Array> {
|
||||||
|
const iterator = source[Symbol.asyncIterator]();
|
||||||
|
const te = new TextEncoder();
|
||||||
|
return new ReadableStream<Uint8Array>({
|
||||||
|
async pull(controller) {
|
||||||
|
try {
|
||||||
|
const { value, done } = await iterator.next();
|
||||||
|
|
||||||
|
if (done) {
|
||||||
|
controller.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const encoded = encoder.encode(value);
|
||||||
|
const bytes = typeof encoded === 'string' ? te.encode(encoded) : encoded;
|
||||||
|
controller.enqueue(bytes);
|
||||||
|
} catch (err) {
|
||||||
|
controller.error(err);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
async cancel() {
|
||||||
|
await iterator.return?.();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { asReadableStream } from '../src/http/web';
|
||||||
|
import { sseEncoder } from '../src/encoders';
|
||||||
|
|
||||||
|
async function* nums() { yield { n: 1 }; yield { n: 2 }; }
|
||||||
|
|
||||||
|
describe('asReadableStream', () => {
|
||||||
|
it('encodes each yielded value with the encoder', async () => {
|
||||||
|
const rs = asReadableStream(nums(), sseEncoder);
|
||||||
|
const text = await new Response(rs).text();
|
||||||
|
expect(text).toContain('data: {"n":1}');
|
||||||
|
expect(text).toContain('data: {"n":2}');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('cancels the source iterator when the stream is cancelled', async () => {
|
||||||
|
let returned = false;
|
||||||
|
async function* forever() { try { while (true) yield { t: 1 }; } finally { returned = true; } }
|
||||||
|
const rs = asReadableStream(forever(), sseEncoder);
|
||||||
|
const reader = rs.getReader();
|
||||||
|
await reader.read();
|
||||||
|
await reader.cancel();
|
||||||
|
await new Promise((r) => setTimeout(r, 10));
|
||||||
|
expect(returned).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user