wretch
Version:
A tiny wrapper built around fetch with an intuitive syntax.
60 lines • 1.94 kB
JavaScript
/**
* Adds the ability to monitor progress when downloading a response.
*
* _Compatible with all platforms implementing the [TransformStream WebAPI](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream#browser_compatibility)._
*
* ```js
* import ProgressAddon from "wretch/addons/progress"
*
* wretch("some_url")
* // Register the addon
* .addon(ProgressAddon())
* .get()
* // Log the progress as a percentage of completion
* .progress((loaded, total) => console.log(`${(loaded / total * 100).toFixed(0)}%`))
* ```
*/
const progress = () => {
const cb = {
ref: null
};
const transformMiddleware = next => (url, opts) => {
let loaded = 0;
let total = 0;
return next(url, opts).then(response => {
try {
const contentLength = response.headers.get("content-length");
total = contentLength ? +contentLength : null;
const transform = new TransformStream({
transform(chunk, controller) {
loaded += chunk.length;
if (total < loaded) {
total = loaded;
}
if (cb.ref) {
cb.ref(loaded, total);
}
controller.enqueue(chunk);
}
});
return new Response(response.body.pipeThrough(transform), response);
}
catch (e) {
return response;
}
});
};
return {
beforeRequest(wretch) {
return wretch._middlewares.push(transformMiddleware);
},
resolver: {
progress(onProgress) {
cb.ref = onProgress;
return this;
}
},
};
};
export default progress;
//# sourceMappingURL=progress.js.map