-
Notifications
You must be signed in to change notification settings - Fork 1
/
New helper with type
58 lines (48 loc) · 1.76 KB
/
New helper with type
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
// RealmDatabase.ts
import Realm, { ObjectClass, ObjectSchema } from 'realm';
import realmConfig from './realmConfig';
class RealmDatabase {
private static instance: RealmDatabase;
private realm: Realm;
private constructor() {
this.realm = new Realm(realmConfig);
}
public static getInstance(): RealmDatabase {
if (!RealmDatabase.instance) {
RealmDatabase.instance = new RealmDatabase();
}
return RealmDatabase.instance;
}
public createObject<T extends Realm.Object>(schemaName: string, data: Partial<T>): void {
this.realm.write(() => {
this.realm.create(schemaName, data);
});
}
public getObject<T extends Realm.Object>(schemaName: string, primaryKey: string): T | undefined {
const result = this.realm.objectForPrimaryKey<T>(schemaName, primaryKey);
return result ? JSON.parse(JSON.stringify(result)) : undefined; // Deep clone to convert Realm.Object to plain object
}
public getAllObjects<T extends Realm.Object>(schemaName: string): T[] {
const results = this.realm.objects<T>(schemaName);
return results.map(result => JSON.parse(JSON.stringify(result))); // Deep clone to convert Realm.Object to plain object
}
public updateObject<T extends Realm.Object>(schemaName: string, data: Partial<T>): void {
this.realm.write(() => {
this.realm.create(schemaName, data, Realm.UpdateMode.Modified);
});
}
public deleteObject(schemaName: string, primaryKey: string): void {
this.realm.write(() => {
const objectToDelete = this.realm.objectForPrimaryKey(schemaName, primaryKey);
if (objectToDelete) {
this.realm.delete(objectToDelete);
}
});
}
public close(): void {
if (!this.realm.isClosed) {
this.realm.close();
}
}
}
export default RealmDatabase;