lukeed / lukeed/fetch-event-stream
Convert `events` to `ReadableStream` ?
- Dominant language
- TypeScript
- Stars
- 438
- Forks
- 6
- PR merge metrics
- No merged PRs in 30d
Description
Perhaps [`events()`](https://deno.land/x/fetch_event_stream@0.1.1/mod.ts?s=events) should be a `ReadableStream` of `ServerSentMessage`s instead of an AsyncIterator.
Practically, the stream could still be used with this syntax:
```js
for await (let event of events(res)) {
console.log('<<', event.data);
}
```
The difference would be that a ReadableStream (I _think_, although am fairly confident) performs better _and_ you have the ability to easily pipe it to some Writer or Transformer stream. For example, imagine:
```js
events(res).pipeThrough(new JSONTransformer).pipeTo(...)
```
To do the same now, with the AsyncIterator, you have to manually loop the iterable and apply your work; or, convert it to a `ReadableStream` to be able to do any pipe-work (mentioned above):
```ts
// AKA, current implementation
let gen = events(res) as AsyncGenerator;
// Option 1, where supported
let rs1 = ReadableStream.from(gen);
// Option 2, manual workaround
let rs2 = new ReadableStream({
async pull(ctrl) {
let { value, done } = await gen.next();
if (done) ctrl.close();
else ctrl.enqueue(value);
},
});
}
```
### Considerations
* `ReadableStream`s aren't treated as AsyncIterators everywhere yet; see [support](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream#browser_compatibility). As of now, only Deno >= 1.0, Node >= 16.5.0, and Firefox >= 110 support this feature.
* `AsyncGenerator`s (what `events()` currently returns) is [supported in significantly more places](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncIterator#browser_compatibility).
_This may be reason alone to keep what's here._
* The `ReadableStream.from` shortcut is available in Deno >= 1.35, Node >= 20.6.0, and Firefix >= 20.6. However, there's an easy manual workaround when this static method isn't available (see above)
Contributor guide
No contributing guide indexed for this repository
Research direction
Start by reading the events() entry point and its current AsyncIterator contract. Compare that API with the ReadableStream piping and compatibility considerations described here, then review the comment thread for a decision. Done means the return-type direction is settled and the documented behavior and compatibility expectations are clear.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- api, web-dev
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100