-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfirebase-client.js
108 lines (98 loc) · 2.38 KB
/
firebase-client.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
/**
* @fileoverview A Promise-based Firebase client.
*/
'use strict'
class FirebaseClient {
/**
* @param {Firebase} firebase The base Firebase reference.
* @param {Function} Promise A Promise implementation to use.
*/
constructor(firebase, Promise) {
this._firebase = firebase
this._Promise = Promise
}
/**
* @param {string|Array.<string>} path
* @param {*} value
* @return {!Promise}
*/
set(path, value) {
return new this._Promise((resolve, reject) => {
this.getReference(path).set(value, (err) => {
if (err) reject(err)
else resolve()
})
})
}
/**
* @param {string|Array.<string>} path
* @param {*} updates
* @return {!Promise}
*/
update(path, updates) {
return new this._Promise((resolve, reject) => {
this.getReference(path).update(updates, (err) => {
if (err) reject(err)
else resolve()
})
})
}
/**
* @param {string|Array.<string>} path
* @param {*} value
* @return {!Promise.<string>} The ID of the pushed object
*/
push(path, value) {
return new this._Promise((resolve, reject) => {
const ref = this.getReference(path).push(value, (err) => {
if (err) reject(err)
else resolve(ref.key())
})
})
}
/**
* @param {string|Array.<string>} path
* @return {!Promise.<DataSnapshot>}
*/
get(path) {
return this.query(this.getReference(path))
}
/**
* @param {Firebase} ref
* @return {!Promise.<DataSnapshot>}
*/
query(ref) {
return new this._Promise((resolve, reject) => {
ref.once('value', (snapshot) => {
resolve(snapshot)
}, reject)
})
}
/**
* @param {string} key
* @param {*} value
* @return {!Promise.<DataSnapshot>}
*/
queryChildEqualTo(key, value) {
const queryRef = this.getReference().orderByChild(key).equalTo(value)
return this.query(queryRef)
}
/**
* @param {(string|Array.<string>)=} opt_path
* @return {!Firebase}
*/
getReference(opt_path) {
if (!opt_path) return this._firebase
const path = Array.isArray(opt_path) ? opt_path.join('/') : opt_path
return this._firebase.child(path)
}
/**
* @param {string|Array.<string>} path
* @return {!FirebaseClient}
*/
child(path) {
const ref = this.getReference(path)
return new FirebaseClient(ref, this._Promise)
}
}
module.exports = FirebaseClient