-
Notifications
You must be signed in to change notification settings - Fork 1
/
gun-realm.js
91 lines (88 loc) · 2.82 KB
/
gun-realm.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 keyValRealm from './key-val';
import {KeyValAdapter} from './gun-flint/src/index';
const GunRealm = new KeyValAdapter({
opt: function(context, options) {
},
get: function(key, field, done) {
let db = keyValRealm.objects('KeyVal');
let pairs;
try {
if (field) {
pairs = db.filtered(`key_field == $0`, (key + '_' + field));
} else {
pairs = db.filtered('key == $0', key);
}
let graphRows = pairs.map(row => {
let node = {
key: row.key,
field: row.field,
state: row.state
};
if (row.valType > -1) {
switch (row.valType) {
case 0:
node.val = row.val;
break;
case 1:
node.val = parseInt(row.val);
break;
case 2:
node.val = (row.val === "true");
break;
case 3:
node.val = null;
break;
}
} else {
node.rel = row.rel;
}
return node;
});
done(null, graphRows);
} catch (err) {
done(this.errors.internal)
}
},
put: function(batch, done) {
try {
keyValRealm.write(() => {
let written = 0;
let target = batch.length;
batch.forEach(node => {
node.key_field = node.key + '_' + node.field;
if (node.val !== undefined) {
node.valType = this._determineValType(node.val);
node.val = (node.valType !== 3) ? "" + node.val : "";
} else {
node.valType = -1;
}
node.rel = typeof node.rel === "string" ? node.rel : "";
keyValRealm.create('KeyVal', node, true);
});
done(null);
});
} catch (e) {
console.error(e);
done(e);
}
},
_determineValType: function(val) {
let type = -1;
switch (true) {
case (typeof val === 'string'):
type = 0;
break;
case (typeof val === 'number'):
type = 1;
break;
case (typeof val === 'boolean'):
type = 2;
break;
case (val === null):
type = 3;
break;
}
return type;
}
});
module.exports = GunRealm;