-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgunWrapper.js
94 lines (75 loc) · 2.22 KB
/
gunWrapper.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
import Gun from "https://cdn.skypack.dev/gun";
const GUN_SERVER = "https://d6a054a208765f61a368c5f3fe73e4c5.loophole.site/gun"
let gunInstance = {}
const gunDB = {
initialize: (serverPath=GUN_SERVER) => {
gunInstance = Gun(serverPath)
},
traverseDB: async (pathKeys = []) => {
let parentObj = undefined
if (pathKeys.length === 0) {
parentObj = gunInstance
} else {
for (let prop of pathKeys) {
parentObj = parentObj ? await parentObj.get(prop) : await gunInstance.get(prop)
}
}
return parentObj
},
createObject: (pathKeys = [], newKey, value) => {
return gunDB.updateObject([...pathKeys, newKey], value)
},
updateObject: (pathKeys=[], newValue) => {
return new Promise(async (resolve, reject) => {
let parentObj = await gunDB.traverseDB(pathKeys)
if (typeof(newValue) !== 'undefined') {
parentObj.put(newValue, (ack) => {
if (ack.err) {
reject(ack.err)
} else {
resolve()
}
})
} else {
resolve()
}
})
},
// addToList: async (pathKeys = [], newKey, value) => {
// return new Promise((resolve, reject) => {
// parentObj = gunDB.traverseDB(pathKeys)
// newObj = gunDB.get(newKey)
// newObj.put(value)
// parentObj.set(newObj, (ack) => {
// if (ack.err) {
// reject(ack.err)
// } else {
// resolve()
// }
// })
// })
// },
getObject: (pathKeys = []) => {
return new Promise(async (resolve) => {
let parentObj = await gunDB.traverseDB(pathKeys)
parentObj.once((data) => {
if (typeof (data) === 'object' && '_' in data) {
const { _, ...result } = data
resolve(result)
} else {
resolve(data)
}
})
})
},
trackObject: async (pathKeys=[], cb, filter=true) => {
let parentObj = await gunDB.traverseDB(pathKeys)
parentObj.on(cb, filter)
},
untrackObject: async (pathKeys=[]) => {
let parentObj = await gunDB.traverseDB(pathKeys)
parentObj.off()
},
removeFromList: (pathKeys = []) => gunDB.updateObject(pathKeys, null)
}
export default gunDB