-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
71 lines (60 loc) · 1.99 KB
/
index.js
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
import * as FileSystem from 'expo-file-system';
export const DocumentDir = FileSystem.documentDirectory;
export const CacheDir = FileSystem.cacheDirectory;
const resolvePath = (...paths) => paths.join('/').split('/').filter(part => part && part !== '.').join('/');
// Wrap function to support both Promise and callback
async function withCallback(callback, func) {
try {
const result = await func();
if (callback) {
callback(null, result);
}
return result;
} catch (err) {
if (callback) {
callback(err);
} else {
throw err;
}
}
}
const FSStorage = (location = DocumentDir, folder = 'reduxPersist') => {
const baseFolder = resolvePath(location, folder);
const pathForKey = key => resolvePath(baseFolder, encodeURIComponent(key));
const setItem = (key, value, callback) => withCallback(callback, async () => {
const { exists } = await FileSystem.getInfoAsync(baseFolder);
if (exists == false) {
await FileSystem.makeDirectoryAsync(baseFolder, {
intermediates: true
});
}
await FileSystem.writeAsStringAsync(pathForKey(key), value);
});
const getItem = (key, callback) => withCallback(callback, async () => {
const pathKey = pathForKey(key);
const { exists } = await FileSystem.getInfoAsync(pathKey);
if (exists) {
return await FileSystem.readAsStringAsync(pathKey);
}
});
const removeItem = (key, callback) => withCallback(callback, async () => {
await FileSystem.deleteAsync(pathForKey(key), {
idempotent: true
});
});
const getAllKeys = callback => withCallback(callback, async () => {
await FileSystem.makeDirectoryAsync(baseFolder, {
intermediates: true
});
const baseFolderLength = baseFolder.length;
const files = await FileSystem.readDirectoryAsync(baseFolder);
return files.map(fileUri => decodeURIComponent(fileUri.substring(baseFolderLength)));
});
return {
setItem,
getItem,
removeItem,
getAllKeys
};
};
export default FSStorage;