Added promise progress
All checks were successful
Build / Build NPM Project (push) Successful in 17s
Build / Tag Version (push) Successful in 4s
Build / Publish (push) Successful in 7s

This commit is contained in:
Zakary Timson 2024-04-27 23:09:12 -04:00
parent 0985ff145e
commit 86196c3feb
6 changed files with 28 additions and 78 deletions

View File

@ -1,6 +1,6 @@
{
"name": "@ztimson/utils",
"version": "0.8.2",
"version": "0.9.0",
"description": "Utility library",
"author": "Zak Timson",
"license": "MIT",

View File

@ -1,11 +1,3 @@
import {TypedEmitter, TypedEvents} from './emitter';
export type DownloadEvents = TypedEvents & {
complete: (blob: Blob) => any;
failed: (error: Error) => any;
progress: (progress: number) => any;
}
export function download(href: any, name: string) {
const a = document.createElement('a');
a.href = href;
@ -14,40 +6,3 @@ export function download(href: any, name: string) {
a.click();
document.body.removeChild(a);
}
/**
* Download a URL using fetch so progress can be tracked. Uses Typed Emitter to emit a "progress" &
* "complete" event.
*
* @param {string} url
* @param {string} downloadName
* @return {TypedEmitter<DownloadEvents>}
*/
export function downloadProgress(url: string, downloadName?: string) {
const progress = new TypedEmitter<DownloadEvents>();
fetch(url).then(response => {
if(!response.ok) return progress.emit('failed', new Error(response.statusText));
const contentLength = response.headers.get('Content-Length') || '0';
const total = parseInt(contentLength, 10);
let chunks: any[] = [], loaded = 0;
const reader = response.body?.getReader();
reader?.read().then(function processResult(result) {
if(result.done) {
const blob = new Blob(chunks);
if(downloadName) {
const url = URL.createObjectURL(blob);
download(url, downloadName);
URL.revokeObjectURL(url);
}
progress.emit('complete', blob);
} else {
const chunk = result.value;
chunks.push(chunk);
loaded += chunk.length;
progress.emit('progress', loaded / total);
reader.read().then(processResult);
}
});
}).catch(err => progress.emit('failed', err));
return progress;
}

View File

@ -6,7 +6,7 @@ export * from './errors';
export * from './logger';
export * from './misc';
export * from './objects';
export * from './promise-progress';
export * from './string';
export * from './time';
export * from './upload';
export * from './xhr';

26
src/promise-progress.ts Normal file
View File

@ -0,0 +1,26 @@
export type ProgressCallback = (progress: number) => any;
export class PromiseProgress<T> extends Promise<T> {
private listeners: ProgressCallback[] = [];
private _progress = 0;
get progress() { return this._progress; }
set progress(p: number) {
if(p == this._progress) return;
this._progress = p;
this.listeners.forEach(l => l(p));
}
constructor(executor: (resolve: (value: T) => any, reject: (reason: any) => void, progress: (progress: number) => any) => void) {
super((resolve, reject) => executor(
(value: T) => resolve(value),
(reason: any) => reject(reason),
(progress: number) => this.progress = progress
));
}
onProgress(callback: ProgressCallback) {
this.listeners.push(callback);
return this;
}
}

View File

@ -1,30 +0,0 @@
import {TypedEmitter, TypedEvents} from './emitter';
export type UploadEvents = TypedEvents & {
complete: () => any;
failed: (err: Error) => any;
progress: (progress: number) => any;
}
export function uploadProgress(files : File | File[], url: string) {
const xhr = new XMLHttpRequest();
const progress = new TypedEmitter<UploadEvents>();
const formData = new FormData();
(Array.isArray(files) ? files : [files])
.forEach(f => formData.append('file', f));
xhr.upload.addEventListener("progress", (event) => {
if(event.lengthComputable) progress.emit('progress', event.loaded / event.total);
});
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if(xhr.status >= 200 && xhr.status < 300) progress.emit('complete');
else progress.emit('failed', new Error(xhr.responseText));
}
};
xhr.open("POST", url, true);
xhr.send(formData);
return progress;
}

View File

@ -1,4 +1,3 @@
import {TypedEmitter, TypedEvents} from './emitter.ts';
import {clean} from './objects';
export type Interceptor = (request: Response, next: () => void) => void;