浏览代码

Change API `flush` to `unlink`

Ben Hsieh 9 年前
父节点
当前提交
f572b9b856
共有 3 个文件被更改,包括 76 次插入21 次删除
  1. 4
    9
      src/android/src/main/java/com/RNFetchBlob/RNFetchBlob.java
  2. 67
    11
      src/index.js
  3. 5
    1
      src/ios/RNFetchBlob/RNFetchBlob.m

+ 4
- 9
src/android/src/main/java/com/RNFetchBlob/RNFetchBlob.java 查看文件

59
     }
59
     }
60
 
60
 
61
     @ReactMethod
61
     @ReactMethod
62
-    public void flush(String taskId) {
62
+    public void unlink(String path, Callback callback) {
63
         try {
63
         try {
64
-            new File(RNFetchBlobFS.getTmpPath(this.getReactApplicationContext(), taskId)).delete();
64
+            new File(RNFetchBlobFS.getTmpPath(this.getReactApplicationContext(), path)).delete();
65
+            callback.invoke(null);
65
         } catch(Exception err) {
66
         } catch(Exception err) {
66
-            WritableMap args = Arguments.createMap();
67
-            args.putString("event", "error");
68
-            args.putString("detail", err.getMessage());
69
-            this.getReactApplicationContext()
70
-                    .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
71
-                    .emit("RNFetchBlobMessage", args);
67
+            callback.invoke("Failed to remove file or directory at " + path);
72
         }
68
         }
73
     }
69
     }
74
 
70
 
163
 
159
 
164
             // set params
160
             // set params
165
             RequestParams params = new RequestParams();
161
             RequestParams params = new RequestParams();
166
-//            ByteArrayEntity entity = null;
167
             HttpEntity entity = null;
162
             HttpEntity entity = null;
168
             // set params
163
             // set params
169
             for (String paramName : uri.getQueryParameterNames()) {
164
             for (String paramName : uri.getQueryParameterNames()) {

+ 67
- 11
src/index.js 查看文件

1
 /**
1
 /**
2
+ * @name react-native-fetch-blob
2
  * @author wkh237
3
  * @author wkh237
3
  * @version 0.5.0
4
  * @version 0.5.0
4
  * @flow
5
  * @flow
14
   RNFetchBlobNative,
15
   RNFetchBlobNative,
15
   RNFetchBlobConfig,
16
   RNFetchBlobConfig,
16
   RNFetchBlobStream
17
   RNFetchBlobStream
17
-}from './types'
18
+} from './types'
18
 import base64 from 'base-64'
19
 import base64 from 'base-64'
19
 
20
 
20
-// const emitter = (Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter)
21
 const emitter = DeviceEventEmitter
21
 const emitter = DeviceEventEmitter
22
 const RNFetchBlob:RNFetchBlobNative = NativeModules.RNFetchBlob
22
 const RNFetchBlob:RNFetchBlobNative = NativeModules.RNFetchBlob
23
 const pathPrefix = Platform.OS === 'android' ? 'file://' : ''
23
 const pathPrefix = Platform.OS === 'android' ? 'file://' : ''
24
 
24
 
25
+// register message channel event handler.
25
 emitter.addListener("RNFetchBlobMessage", (e) => {
26
 emitter.addListener("RNFetchBlobMessage", (e) => {
26
-
27
   if(e.event === 'warn') {
27
   if(e.event === 'warn') {
28
     console.warn(e.detail)
28
     console.warn(e.detail)
29
   }
29
   }
33
   else {
33
   else {
34
     console.log("RNFetchBlob native message", e.detail)
34
     console.log("RNFetchBlob native message", e.detail)
35
   }
35
   }
36
-
37
 })
36
 })
38
 
37
 
39
 // Show warning if native module not detected
38
 // Show warning if native module not detected
45
   )
44
   )
46
 }
45
 }
47
 
46
 
47
+/**
48
+ * Get path of system directories.
49
+ * @return {object} Map contains PictureDir, MovieDir, DocumentDir, CacheDir,
50
+ * MusicDir, and DCIMDir, some directory might not be supported by platform.
51
+ */
48
 function getSystemDirs() {
52
 function getSystemDirs() {
49
   return new Promise((resolve, reject) => {
53
   return new Promise((resolve, reject) => {
50
     try {
54
     try {
60
 
64
 
61
 }
65
 }
62
 
66
 
67
+/**
68
+ * Calling this method will inject configurations into followed `fetch` method.
69
+ * @param  {RNFetchBlobConfig} options
70
+ *         Fetch API configurations, contains the following options :
71
+ *         @property {boolean} fileCache
72
+ *                   When fileCache is `true`, response data will be saved in
73
+ *                   storage with a random generated file name, rather than
74
+ *                   a BASE64 encoded string.
75
+ *         @property {string} appendExt
76
+ *                   Set this property to change file extension of random-
77
+ *                   generated file name.
78
+ *         @property {string} path
79
+ *                   If this property has a valid string format, resonse data
80
+ *                   will be saved to specific file path. Default string format
81
+ *                   is : `RNFetchBlob-file://path-to-file`
82
+ *
83
+ * @return {function} This method returns a `fetch` method instance.
84
+ */
63
 function config (options:RNFetchBlobConfig) {
85
 function config (options:RNFetchBlobConfig) {
64
   return { fetch : fetch.bind(options) }
86
   return { fetch : fetch.bind(options) }
65
 }
87
 }
66
 
88
 
67
-// Promise wrapper function
68
-function fetch(...args:any) {
89
+/**
90
+ * Create a HTTP request by settings, the `this` context is a `RNFetchBlobConfig` object.
91
+ * @param  {string} method HTTP method, should be `GET`, `POST`, `PUT`, `DELETE`
92
+ * @param  {string} url Request target url string.
93
+ * @param  {object} headers HTTP request headers.
94
+ * @param  {string} body
95
+ *         Request body, can be either a BASE64 encoded data string,
96
+ *         or a file path with prefix `RNFetchBlob-file://` (can be changed)
97
+ * @return {Promise}
98
+ *         This promise instance also contains a Customized method `progress`for
99
+ *         register progress event handler.
100
+ */
101
+function fetch(...args:any):Promise {
69
 
102
 
70
   // create task ID for receiving progress event
103
   // create task ID for receiving progress event
71
   let taskId = getUUID()
104
   let taskId = getUUID()
100
 
133
 
101
   })
134
   })
102
 
135
 
136
+  // extend Promise object, add a `progress` method for register progress event
137
+  // handler.
103
   promise.progress = (fn) => {
138
   promise.progress = (fn) => {
104
     promise.onProgress = fn
139
     promise.onProgress = fn
105
     return promise
140
     return promise
109
 
144
 
110
 }
145
 }
111
 
146
 
147
+/**
148
+ * Create file stream from file at `path`.
149
+ * @param  {String} path   The file path.
150
+ * @param  {String} encoding Data encoding, should be one of `base64`, `utf8`, `ascii`
151
+ * @param  {String} bufferSize Size of stream buffer.
152
+ * @return {RNFetchBlobStream} RNFetchBlobStream stream instance.
153
+ */
112
 function openReadStream(
154
 function openReadStream(
113
   path:string,
155
   path:string,
114
   encoding:'utf8' | 'ascii' | 'base64',
156
   encoding:'utf8' | 'ascii' | 'base64',
146
     if (event === 'error' || event === 'end') {
188
     if (event === 'error' || event === 'end') {
147
       subscription.remove()
189
       subscription.remove()
148
     }
190
     }
149
-
150
   })
191
   })
151
 
192
 
152
   RNFetchBlob.readStream(path, encoding, bufferSize || 0)
193
   RNFetchBlob.readStream(path, encoding, bufferSize || 0)
154
 
195
 
155
 }
196
 }
156
 
197
 
198
+/**
199
+ * Remove file at path.
200
+ * @param  {string}   path:string Path of target file.
201
+ * @return {Promise}
202
+ */
203
+function unlink(path:string):Promise {
204
+  return new Promise((resolve, reject) => {
205
+    RNFetchBlob.unlink(path, (err) => {
206
+      if(err)
207
+        reject(err)
208
+      else
209
+        resolve()
210
+    })
211
+  })
212
+}
213
+
157
 /**
214
 /**
158
  * RNFetchBlob response object class.
215
  * RNFetchBlob response object class.
159
  */
216
  */
209
     }
266
     }
210
     /**
267
     /**
211
      * Remove cahced file
268
      * Remove cahced file
212
-     * @return {void}
269
+     * @return {Promise}
213
      */
270
      */
214
     this.flush = () => {
271
     this.flush = () => {
215
-      RNFetchBlob.flush(this.path())
272
+      return unlink(this.path())
216
     }
273
     }
217
     /**
274
     /**
218
      * get path of response temp file
275
      * get path of response temp file
238
         return null
295
         return null
239
       }
296
       }
240
     }
297
     }
241
-
242
   }
298
   }
243
 
299
 
244
 }
300
 }
251
 }
307
 }
252
 
308
 
253
 export default {
309
 export default {
254
-  fetch, base64, config, getSystemDirs, openReadStream
310
+  fetch, base64, config, getSystemDirs, readStream, unlink
255
 }
311
 }

+ 5
- 1
src/ios/RNFetchBlob/RNFetchBlob.m 查看文件

591
     [fileStream readWithPath:path useEncoding:encoding bufferSize:bufferSize];
591
     [fileStream readWithPath:path useEncoding:encoding bufferSize:bufferSize];
592
 }
592
 }
593
 
593
 
594
-RCT_EXPORT_METHOD(flush:(NSString *)path) {
594
+RCT_EXPORT_METHOD(unlink:(NSString *)path callback:(RCTResponseSenderBlock) callback) {
595
     NSError * error = nil;
595
     NSError * error = nil;
596
     NSString * tmpPath = nil;
596
     NSString * tmpPath = nil;
597
     [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
597
     [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
598
+    if(error == nil)
599
+        callback(@[[NSNull null]]);
600
+    else
601
+        callback(@[[NSString stringWithFormat:@"failed to unlink file or path at %@", path]]);
598
 }
602
 }
599
 
603
 
600
 RCT_EXPORT_METHOD(getEnvironmentDirs:(RCTResponseSenderBlock) callback) {
604
 RCT_EXPORT_METHOD(getEnvironmentDirs:(RCTResponseSenderBlock) callback) {