Browse Source

Change API `flush` to `unlink`

Ben Hsieh 8 years ago
parent
commit
f572b9b856

+ 4
- 9
src/android/src/main/java/com/RNFetchBlob/RNFetchBlob.java View File

@@ -59,16 +59,12 @@ public class RNFetchBlob extends ReactContextBaseJavaModule {
59 59
     }
60 60
 
61 61
     @ReactMethod
62
-    public void flush(String taskId) {
62
+    public void unlink(String path, Callback callback) {
63 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 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,7 +159,6 @@ public class RNFetchBlob extends ReactContextBaseJavaModule {
163 159
 
164 160
             // set params
165 161
             RequestParams params = new RequestParams();
166
-//            ByteArrayEntity entity = null;
167 162
             HttpEntity entity = null;
168 163
             // set params
169 164
             for (String paramName : uri.getQueryParameterNames()) {

+ 67
- 11
src/index.js View File

@@ -1,4 +1,5 @@
1 1
 /**
2
+ * @name react-native-fetch-blob
2 3
  * @author wkh237
3 4
  * @version 0.5.0
4 5
  * @flow
@@ -14,16 +15,15 @@ import type {
14 15
   RNFetchBlobNative,
15 16
   RNFetchBlobConfig,
16 17
   RNFetchBlobStream
17
-}from './types'
18
+} from './types'
18 19
 import base64 from 'base-64'
19 20
 
20
-// const emitter = (Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter)
21 21
 const emitter = DeviceEventEmitter
22 22
 const RNFetchBlob:RNFetchBlobNative = NativeModules.RNFetchBlob
23 23
 const pathPrefix = Platform.OS === 'android' ? 'file://' : ''
24 24
 
25
+// register message channel event handler.
25 26
 emitter.addListener("RNFetchBlobMessage", (e) => {
26
-
27 27
   if(e.event === 'warn') {
28 28
     console.warn(e.detail)
29 29
   }
@@ -33,7 +33,6 @@ emitter.addListener("RNFetchBlobMessage", (e) => {
33 33
   else {
34 34
     console.log("RNFetchBlob native message", e.detail)
35 35
   }
36
-
37 36
 })
38 37
 
39 38
 // Show warning if native module not detected
@@ -45,6 +44,11 @@ if(!RNFetchBlob || !RNFetchBlob.fetchBlobForm || !RNFetchBlob.fetchBlob) {
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 52
 function getSystemDirs() {
49 53
   return new Promise((resolve, reject) => {
50 54
     try {
@@ -60,12 +64,41 @@ function getSystemDirs() {
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 85
 function config (options:RNFetchBlobConfig) {
64 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 103
   // create task ID for receiving progress event
71 104
   let taskId = getUUID()
@@ -100,6 +133,8 @@ function fetch(...args:any) {
100 133
 
101 134
   })
102 135
 
136
+  // extend Promise object, add a `progress` method for register progress event
137
+  // handler.
103 138
   promise.progress = (fn) => {
104 139
     promise.onProgress = fn
105 140
     return promise
@@ -109,6 +144,13 @@ function fetch(...args:any) {
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 154
 function openReadStream(
113 155
   path:string,
114 156
   encoding:'utf8' | 'ascii' | 'base64',
@@ -146,7 +188,6 @@ function openReadStream(
146 188
     if (event === 'error' || event === 'end') {
147 189
       subscription.remove()
148 190
     }
149
-
150 191
   })
151 192
 
152 193
   RNFetchBlob.readStream(path, encoding, bufferSize || 0)
@@ -154,6 +195,22 @@ function openReadStream(
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 215
  * RNFetchBlob response object class.
159 216
  */
@@ -209,10 +266,10 @@ class FetchBlobResponse {
209 266
     }
210 267
     /**
211 268
      * Remove cahced file
212
-     * @return {void}
269
+     * @return {Promise}
213 270
      */
214 271
     this.flush = () => {
215
-      RNFetchBlob.flush(this.path())
272
+      return unlink(this.path())
216 273
     }
217 274
     /**
218 275
      * get path of response temp file
@@ -238,7 +295,6 @@ class FetchBlobResponse {
238 295
         return null
239 296
       }
240 297
     }
241
-
242 298
   }
243 299
 
244 300
 }
@@ -251,5 +307,5 @@ function getUUID() {
251 307
 }
252 308
 
253 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 View File

@@ -591,10 +591,14 @@ RCT_EXPORT_METHOD(readStream:(NSString *)path withEncoding:(NSString *)encoding
591 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 595
     NSError * error = nil;
596 596
     NSString * tmpPath = nil;
597 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 604
 RCT_EXPORT_METHOD(getEnvironmentDirs:(RCTResponseSenderBlock) callback) {