forked from reactnativecn/react-native-http-cache
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
63 lines (55 loc) · 1.69 KB
/
index.js
File metadata and controls
63 lines (55 loc) · 1.69 KB
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
/**
* Created by tdzl2_000 on 2015-12-29.
*/
import { NativeModules } from 'react-native';
import promisify from 'es6-promisify';
const native = NativeModules.HttpCache;
// Used only with promisify. Transform callback to promise result.
function translateError(err, result) {
if (!err) {
return this.resolve(result);
}
if (typeof err === 'object') {
if (err instanceof Error) {
return this.reject(ret);
}
const {message, ...other} = err;
return this.reject(Object.assign(new Error(err.message), other));
} else if (typeof err === 'string') {
return this.reject(new Error(err));
}
this.reject(Object.assign(new Error(), { origin: err }));
}
function wrapApi(nativeFunc, argCount) {
if (!nativeFunc) {
return undefined;
}
const promisified = promisify(nativeFunc, translateError);
if (argCount != undefined){
return (...args) => {
let _args = args;
if (_args.length < argCount) {
_args[argCount - 1] = undefined;
} else if (_args.length > argCount){
_args = _args.slice(0, args);
}
return promisified(..._args);
};
} else {
return () => {
return promisified();
};
}
}
export const clearHttpCache = wrapApi(native.clearCache);
export const getHttpCacheSize = wrapApi(native.getHttpCacheSize);
export const clearImageCache = wrapApi(native.clearImageCache);
export const getImageCacheSize = wrapApi(native.getImageCacheSize);
export async function getSize(){
const arr = await Promise.all([getHttpCacheSize(), getImageCacheSize()]);
// Get sum of all cache type.
return arr.reduce((a,b)=>a+b, 0);
}
export async function clear(){
await Promise.all([clearHttpCache(), clearImageCache()]);
}