2018-07-19 23:46:12 +02:00
|
|
|
/* global ReadableStream TransformStream */
|
2018-07-17 20:40:01 +02:00
|
|
|
|
2018-07-24 00:12:58 +02:00
|
|
|
export function transformStream(readable, transformer, oncancel) {
|
2018-07-19 23:46:12 +02:00
|
|
|
if (typeof TransformStream === 'function') {
|
|
|
|
return readable.pipeThrough(new TransformStream(transformer));
|
|
|
|
}
|
2018-07-19 01:39:14 +02:00
|
|
|
const reader = readable.getReader();
|
2018-07-23 18:49:16 +02:00
|
|
|
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;
|
2018-07-23 18:49:16 +02:00
|
|
|
const wrappedController = {
|
2018-07-19 01:39:14 +02:00
|
|
|
enqueue(d) {
|
|
|
|
enqueued = true;
|
|
|
|
controller.enqueue(d);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
while (!enqueued) {
|
2018-07-23 18:49:16 +02:00
|
|
|
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();
|
|
|
|
}
|
2018-07-23 18:49:16 +02:00
|
|
|
await transformer.transform(data.value, wrappedController);
|
2018-07-19 01:39:14 +02:00
|
|
|
}
|
|
|
|
},
|
2018-07-24 00:12:58 +02:00
|
|
|
cancel(reason) {
|
|
|
|
readable.cancel(reason);
|
|
|
|
if (oncancel) {
|
|
|
|
oncancel(reason);
|
|
|
|
}
|
2018-07-19 01:39:14 +02:00
|
|
|
}
|
|
|
|
});
|
2018-07-17 20:40:01 +02:00
|
|
|
}
|