Repository navigation
Expand file tree
/
Copy pathdbAPI.js
More file actions
64 lines (59 loc) · 1.84 KB
/
Copy pathdbAPI.js
File metadata and controls
64 lines (59 loc) · 1.84 KB
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
//LAZY-INITIALIZING FIREBASE PROXY
var API = function(db) {
var self = this
self.servers = db.collection('servers')
self.cache = {}
self.set = function(id, opts, cb) {
var docRef = self.servers.doc(id);
var setter = docRef.set(opts).then(function(ref) {
cb(null, ref)
}).catch(function(err) { cb(err) })
}
self.update = function(id, opts, cb) {
var docRef = self.servers.doc(id);
var update = docRef.update(opts).then(function(ref) {
cb(null, ref)
}).catch(function(err) { cb(err) })
}
self.get = function(id, cb) {
if (self.cache[id]) {
cb(null, self.cache[id])
return
}
var docRef = self.servers.doc(id);
if (!docRef) {
cb(404)
return
}
docRef.get()
.then(function(doc) {
if (doc.exists) {
var dat = doc.data()
self.cache[id] = dat
cb(null, dat)
}
else cb(404)
}).catch(function(err) { cb(err) })
}
//shard concurrency
self.servers.onSnapshot(function(querySnapshot) {
querySnapshot.docChanges().forEach(function(change) {
if (change.type === "added") {
//console.log("DATABASE SET::\n", change.doc.data());
var dat = change.doc.data()
if (dat) self.cache[dat.id] = dat
}
if (change.type === "modified") {
var dat = change.doc.data()
console.log("DATABSE MODIFY::\n", dat.id);
if (dat) self.cache[dat.id] = dat
}
/*
if (change.type === "removed") {
console.log("removed: ", change.doc.data());
}
*/
});
});
}
module.exports = API