@cardsjd/storage 0.0.3 → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/storage.js +56 -45
- package/package.json +1 -1
package/lib/storage.js
CHANGED
|
@@ -1,54 +1,65 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Filesystem, Directory, Encoding } from '@capacitor/filesystem';
|
|
2
2
|
|
|
3
3
|
export default class Storage {
|
|
4
|
-
|
|
5
|
-
|
|
4
|
+
constructor(_options) {
|
|
5
|
+
}
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
7
|
+
async load(key) {
|
|
8
|
+
let data = null;
|
|
9
9
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
10
|
+
let dataRaw = null;
|
|
11
|
+
//read from local storage
|
|
12
|
+
try {
|
|
13
|
+
console.log('Storage: read - localStorage');
|
|
14
|
+
if (localStorage && localStorage.getItem) {
|
|
15
|
+
dataRaw = localStorage.getItem(key);
|
|
16
|
+
|
|
17
|
+
}
|
|
18
|
+
} catch (e) {
|
|
19
|
+
console.log('Error in load: ' + e);
|
|
20
|
+
}
|
|
21
|
+
//read file from App Data folder
|
|
22
|
+
if (dataRaw === null) {
|
|
23
|
+
try {
|
|
24
|
+
const contents = await Filesystem.readFile({
|
|
25
|
+
path: key + ".json",
|
|
26
|
+
directory: Directory.Data,
|
|
27
|
+
encoding: Encoding.UTF8,
|
|
28
|
+
});
|
|
29
|
+
if (contents && contents.data) {
|
|
30
|
+
dataRaw = contents.data;
|
|
31
|
+
}
|
|
32
|
+
} catch (e) {
|
|
33
|
+
console.log('Error in load: ' + e);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
if (dataRaw !== null && dataRaw != '{}') {
|
|
37
|
+
try {
|
|
38
|
+
data = JSON.parse(dataRaw);
|
|
39
|
+
} catch (e) {
|
|
40
|
+
data = null; //error in the above string(in this case,yes)!
|
|
41
|
+
}
|
|
26
42
|
|
|
27
|
-
|
|
28
|
-
try {
|
|
29
|
-
data = JSON.parse(dataRaw);
|
|
30
|
-
} catch (e) {
|
|
31
|
-
data = null; //error in the above string(in this case,yes)!
|
|
32
|
-
}
|
|
43
|
+
}
|
|
33
44
|
|
|
34
|
-
|
|
45
|
+
return data;
|
|
46
|
+
}
|
|
35
47
|
|
|
36
|
-
|
|
37
|
-
|
|
48
|
+
async save(key, data) {
|
|
49
|
+
const jsonData = JSON.stringify(data);
|
|
38
50
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
}
|
|
51
|
+
try {
|
|
52
|
+
console.log('Storage: save - localStorage');
|
|
53
|
+
localStorage[key] = jsonData;
|
|
54
|
+
} catch (e) {
|
|
55
|
+
console.warn('save: ' + e);
|
|
56
|
+
}
|
|
57
|
+
//read file from App Data folder
|
|
58
|
+
await Filesystem.writeFile({
|
|
59
|
+
path: key + '.json',
|
|
60
|
+
data: jsonData,
|
|
61
|
+
directory: Directory.Data,
|
|
62
|
+
encoding: Encoding.UTF8,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
54
65
|
}
|