-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathprogress.ts
86 lines (81 loc) · 2.49 KB
/
progress.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { XiorPlugin } from '../types';
export interface XiorProgressOptions {
/** default: 5*1000ms, 5 seconds */
progressDuration?: number;
}
type BrowserProgressEvent = any;
export interface XiorProgressEvent {
loaded: number;
total: number;
progress: number;
bytes?: number;
rate?: number;
estimated?: number;
upload?: boolean;
download?: boolean;
event?: BrowserProgressEvent;
}
export interface XiorProgressRequestOptions extends XiorProgressOptions {
onUploadProgress?: (progressEvent: XiorProgressEvent) => void;
onDownloadProgress?: (progressEvent: XiorProgressEvent) => void;
}
/** @ts-ignore */
declare module 'xior' {
interface XiorRequestConfig extends XiorProgressRequestOptions {}
}
/** upload progress / download progress */
export default function xiorProgressPlugin(options: XiorProgressOptions = {}): XiorPlugin {
const { progressDuration: _progressDuration = 5 * 1000 } = options;
return function (adapter) {
return async (config) => {
const {
progressDuration = _progressDuration,
onUploadProgress,
onDownloadProgress,
} = config as XiorProgressRequestOptions;
// const percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
let interval: ReturnType<typeof setInterval> | undefined;
if (onUploadProgress || onDownloadProgress) {
const total = 1000;
let loaded = 0;
let progress = 0;
const step = total / (progressDuration / 300);
interval = setInterval(() => {
if (progress >= 99) {
return clearInterval(interval);
}
loaded += Math.random() * step;
progress = Math.floor((loaded / total) * 100);
const event: XiorProgressEvent = {
total,
loaded,
progress,
};
if (event.progress >= 99) {
event.progress = 99;
event.loaded = 0.99 * total;
}
onUploadProgress?.(event);
onDownloadProgress?.(event);
}, 300);
}
try {
const res = await adapter(config);
if (onUploadProgress || onDownloadProgress) {
const event: XiorProgressEvent = {
total: 1000,
loaded: 1000,
progress: 100,
};
onUploadProgress?.(event);
onDownloadProgress?.(event);
}
return res;
} catch (e) {
throw e;
} finally {
if (interval) clearInterval(interval);
}
};
};
}