-
Notifications
You must be signed in to change notification settings - Fork 17
/
RealmPersistInterface.js
91 lines (79 loc) · 2.28 KB
/
RealmPersistInterface.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import Realm from 'realm';
class RealmPersistInterface {
constructor() {
this.realm = new Realm({
schema: [{
name: 'Item',
primaryKey: 'name',
properties: {
name: 'string',
content: 'string',
},
}],
});
this.items = this.realm.objects('Item');
}
getItem = (key, callback) => {
try {
const matches = this.items.filtered(`name = "${key}"`);
if (matches.length > 0 && matches[0]) {
callback(null, matches[0].content);
} else {
throw new Error(`Could not get item with key: '${key}'`);
}
} catch (error) {
callback(error);
}
};
setItem = (key, value, callback) => {
try {
this.getItem(key, (error) => {
this.realm.write(() => {
if (error) {
this.realm.create(
'Item',
{
name: key,
content: value,
}
);
} else {
this.realm.create(
'Item',
{
name: key,
content: value,
},
true
);
}
callback();
});
});
} catch (error) {
callback(error);
}
};
removeItem = (key, callback) => {
try {
this.realm.write(() => {
const item = this.items.filtered(`name = "${key}"`);
this.realm.delete(item);
});
} catch (error) {
callback(error);
}
};
getAllKeys = (callback) => {
try {
const keys = this.items.map(
(item) => item.name
);
callback(null, keys);
} catch (error) {
callback(error);
}
};
}
const singleton = new RealmPersistInterface();
export default singleton;