Skip to content

Commit 7f02a64

Browse files
authored
Extend support for useFileOutput to stream (#309)
* Break stream on done event without enqueuing it * Fix doc comment for fetch parameter * Transform URLs in streaming responses when useFileOutput is enabled * Revert 'Break stream on done event without enqueuing it' * Default to useFileOutput = true for readable streams
1 parent af9d6e2 commit 7f02a64

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

lib/stream.js

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -48,15 +48,18 @@ class ServerSentEvent {
4848
* @param {string} config.url The URL to connect to.
4949
* @param {typeof fetch} [config.fetch] The URL to connect to.
5050
* @param {object} [config.options] The EventSource options.
51+
* @param {boolean} [config.options.useFileOutput] Whether to use the file output stream.
5152
* @returns {ReadableStream<ServerSentEvent> & AsyncIterable<ServerSentEvent>}
5253
*/
5354
function createReadableStream({ url, fetch, options = {} }) {
55+
const { useFileOutput = true, headers = {}, ...initOptions } = options;
56+
5457
return new ReadableStream({
5558
async start(controller) {
5659
const init = {
57-
...options,
60+
...initOptions,
5861
headers: {
59-
...options.headers,
62+
...headers,
6063
Accept: "text/event-stream",
6164
},
6265
};
@@ -84,9 +87,15 @@ function createReadableStream({ url, fetch, options = {} }) {
8487
break;
8588
}
8689

87-
controller.enqueue(
88-
new ServerSentEvent(event.event, event.data, event.id)
89-
);
90+
let data = event.data;
91+
if (
92+
useFileOutput &&
93+
typeof data === "string" &&
94+
(data.startsWith("https:") || data.startsWith("data:"))
95+
) {
96+
data = createFileOutput({ data, fetch });
97+
}
98+
controller.enqueue(new ServerSentEvent(event.event, data, event.id));
9099

91100
if (event.event === "done") {
92101
break;
@@ -104,7 +113,7 @@ function createReadableStream({ url, fetch, options = {} }) {
104113
*
105114
* @param {object} config
106115
* @param {string} config.url The URL to connect to.
107-
* @param {typeof fetch} [config.fetch] The URL to connect to.
116+
* @param {typeof fetch} [config.fetch] The fetch function.
108117
* @returns {ReadableStream<Uint8Array>}
109118
*/
110119
function createFileOutput({ url, fetch }) {

0 commit comments

Comments
 (0)