|
@@ -4,6 +4,7 @@
|
4
|
4
|
*/
|
5
|
5
|
|
6
|
6
|
import { NativeModules } from 'react-native'
|
|
7
|
+import { DeviceEventEmitter } from 'react-native';
|
7
|
8
|
import base64 from 'base-64'
|
8
|
9
|
|
9
|
10
|
const RNFetchBlob = NativeModules.RNFetchBlob
|
|
@@ -20,20 +21,37 @@ if(RNFetchBlob === void 0) {
|
20
|
21
|
// Promise wrapper function
|
21
|
22
|
const fetch = (...args) => {
|
22
|
23
|
|
|
24
|
+ // create task ID for receiving progress event
|
|
25
|
+ let taskId = getUUID()
|
23
|
26
|
let promise = new Promise((resolve, reject) => {
|
24
|
27
|
|
25
|
28
|
let [method, url, headers, body] = [...args]
|
26
|
29
|
let nativeMethodName = Array.isArray(body) ? 'fetchBlobForm' : 'fetchBlob'
|
27
|
30
|
|
28
|
|
- RNFetchBlob[nativeMethodName](method, url, headers || {}, body, (err, ...data) => {
|
|
31
|
+ let progressEventHandler = (e) => {
|
|
32
|
+ if(e.taskId === taskId && promise.onProgress) {
|
|
33
|
+ promise.onProgress(e.written, e.total)
|
|
34
|
+ }
|
|
35
|
+ }
|
|
36
|
+
|
|
37
|
+ DeviceEventEmitter.addListener('RNFetchBlobProgress' + taskId, progressEventHandler)
|
|
38
|
+
|
|
39
|
+ RNFetchBlob[nativeMethodName](taskId, method, url, headers || {}, body, (err, ...data) => {
|
|
40
|
+
|
|
41
|
+ // task done, remove event listener
|
|
42
|
+ DeviceEventEmitter.removeAllListeners('RNFetchBlobProgress'+taskId)
|
|
43
|
+
|
29
|
44
|
if(err)
|
30
|
45
|
reject(new Error(err, ...data))
|
31
|
46
|
else
|
32
|
47
|
resolve(new FetchBlobResponse(...data))
|
|
48
|
+
|
33
|
49
|
})
|
34
|
50
|
|
35
|
51
|
})
|
36
|
52
|
|
|
53
|
+ promise.onProgress = null
|
|
54
|
+
|
37
|
55
|
return promise
|
38
|
56
|
|
39
|
57
|
}
|
|
@@ -81,6 +99,13 @@ class FetchBlobResponse {
|
81
|
99
|
|
82
|
100
|
}
|
83
|
101
|
|
|
102
|
+function getUUID(){
|
|
103
|
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
|
|
104
|
+ let r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
|
|
105
|
+ return v.toString(16);
|
|
106
|
+ });
|
|
107
|
+}
|
|
108
|
+
|
84
|
109
|
export default {
|
85
|
110
|
fetch, FetchBlobResponse, base64
|
86
|
111
|
}
|