send/app/streams.js

41 lines
1 KiB
JavaScript
Raw Normal View History

2018-07-19 21:46:12 +00:00
/* global ReadableStream TransformStream */
2018-07-17 18:40:01 +00:00
export function transformStream(readable, transformer, oncancel) {
2018-07-19 21:46:12 +00:00
if (typeof TransformStream === 'function') {
return readable.pipeThrough(new TransformStream(transformer));
}
2018-07-18 23:39:14 +00:00
const reader = readable.getReader();
return new ReadableStream({
2018-07-18 23:39:14 +00:00
start(controller) {
if (transformer.start) {
return transformer.start(controller);
}
},
async pull(controller) {
let enqueued = false;
const wrappedController = {
2018-07-18 23:39:14 +00:00
enqueue(d) {
enqueued = true;
controller.enqueue(d);
}
};
while (!enqueued) {
const data = await reader.read();
if (data.done) {
2018-07-18 23:39:14 +00:00
if (transformer.flush) {
await transformer.flush(controller);
}
return controller.close();
}
await transformer.transform(data.value, wrappedController);
2018-07-18 23:39:14 +00:00
}
},
cancel(reason) {
readable.cancel(reason);
if (oncancel) {
oncancel(reason);
}
2018-07-18 23:39:14 +00:00
}
});
2018-07-17 18:40:01 +00:00
}