forked from Osedea/redux-persist-realm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RealmPersistInterface.js
111 lines (93 loc) · 2 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import Realm from 'realm';
var Symbol = require('es6-symbol/polyfill');
const singleton = Symbol();
const singletonEnforcer = Symbol();
export default class RealmPersistInterface {
constructor(enforcer) {
if (enforcer !== singletonEnforcer) {
throw new Error('Cannot construct singleton');
}
this._type = 'RealmPersistInterface';
this.realm = Realm.open({
path: 'redux.realm',
schema: [
{
name: 'Item',
primaryKey: 'name',
properties: {
name: 'string',
content: 'string'
}
}
]
});
}
static get instance() {
if (!this[singleton]) {
this[singleton] = new RealmPersistInterface(singletonEnforcer);
}
return this[singleton];
}
get type() {
return this._type;
}
async check() {
if (!this.items) {
this.realm = await this.realm;
this.items = this.realm.objects('Item');
}
}
async getItem(key) {
await this.check();
return new Promise((resolve, reject) => {
try {
const matches = this.items.filtered(`name = "${key}"`);
if (matches.length > 0 && matches[0]) {
resolve(matches[0].content);
} else {
reject(new Error(`Could not get item with key: '${key}'`));
}
} catch (error) {
reject(error);
}
});
};
async setItem(key, value) {
await this.check();
return new Promise((resolve, reject) => {
try {
this.realm.write(() => {
this.realm.create('Item', { name: key, content: value }, true);
resolve();
});
} catch (error) {
reject(error);
}
});
};
async removeItem(key) {
await this.check();
return new Promise((resolve, reject) => {
try {
this.realm.write(() => {
const item = this.items.filtered(`name = "${key}"`);
this.realm.delete(item);
resolve();
});
} catch (error) {
reject(error);
}
});
};
async getAllKeys() {
await this.check();
return new Promise((resolve, reject) => {
try {
const keys = this.items.map(item => item.name);
resolve(keys);
} catch (error) {
reject(error);
}
});
};
}