mirror of
https://github.com/tenrok/axios.git
synced 2026-06-14 18:42:33 +03:00
feat(adapter): add fetch adapter; (#6371)
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
|
||||
export const streamChunk = function* (chunk, chunkSize) {
|
||||
let len = chunk.byteLength;
|
||||
|
||||
if (!chunkSize || len < chunkSize) {
|
||||
yield chunk;
|
||||
return;
|
||||
}
|
||||
|
||||
let pos = 0;
|
||||
let end;
|
||||
|
||||
while (pos < len) {
|
||||
end = pos + chunkSize;
|
||||
yield chunk.slice(pos, end);
|
||||
pos = end;
|
||||
}
|
||||
}
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
export const readBytes = async function* (iterable, chunkSize) {
|
||||
for await (const chunk of iterable) {
|
||||
yield* streamChunk(ArrayBuffer.isView(chunk) ? chunk : (await encoder.encode(String(chunk))), chunkSize);
|
||||
}
|
||||
}
|
||||
|
||||
export const trackStream = (stream, chunkSize, onProgress, onFinish) => {
|
||||
const iterator = readBytes(stream, chunkSize);
|
||||
|
||||
let bytes = 0;
|
||||
|
||||
return new ReadableStream({
|
||||
type: 'bytes',
|
||||
|
||||
async pull(controller) {
|
||||
const {done, value} = await iterator.next();
|
||||
|
||||
if (done) {
|
||||
controller.close();
|
||||
onFinish();
|
||||
return;
|
||||
}
|
||||
|
||||
let len = value.byteLength;
|
||||
onProgress && onProgress(bytes += len);
|
||||
controller.enqueue(new Uint8Array(value));
|
||||
},
|
||||
cancel(reason) {
|
||||
onFinish(reason);
|
||||
return iterator.return();
|
||||
}
|
||||
}, {
|
||||
highWaterMark: 2
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user