1
0
mirror of https://gitlab.com/timvisee/send.git synced 2024-11-10 13:13:00 +01:00
send/app/streams.js

38 lines
969 B
JavaScript
Raw Normal View History

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