forked from FirebaseExtended/polymerfire
-
Notifications
You must be signed in to change notification settings - Fork 2
/
firebase-document.html
201 lines (169 loc) · 5.45 KB
/
firebase-document.html
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
<!--
@license
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file or at
https://github.com/firebase/polymerfire/blob/master/LICENSE
-->
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="firebase-database-behavior.html">
<script>
'use strict';
/**
* The firebase-document element is an easy way to interact with a firebase
* location as an object and expose it to the Polymer databinding system.
*
* For example:
*
* <firebase-document
* path="/users/[[userId]]/notes/[[noteId]]"
* data="{{noteData}}">
* </firebase-document>
*
* This fetches the `noteData` object from the firebase location at
* `/users/${userId}/notes/${noteId}` and exposes it to the Polymer
* databinding system. Changes to `noteData` will likewise be, sent back up
* and stored.
*
* `<firebase-document>` needs some information about how to talk to Firebase.
* Set this configuration by adding a `<firebase-app>` element anywhere in your
* app.
*/
Polymer({
is: 'firebase-document',
behaviors: [
Polymer.FirebaseDatabaseBehavior
],
attached: function() {
this.__needSetData = true;
this.__refChanged(this.ref, this.ref);
},
detached: function() {
if (this.ref) {
this.ref.off('value', this.__onFirebaseValue, this);
}
},
get isNew() {
return this.disabled || !this.__pathReady(this.path);
},
get zeroValue() {
return {};
},
/**
* Update the path and write this.data to that new location.
*
* Important note: `this.path` is updated asynchronously.
*
* @param {string} parentPath The new firebase location to write to.
* @param {string=} key The key within the parentPath to write `data` to. If
* not given, a random key will be generated and used.
* @return {Promise} A promise that resolves once this.data has been
* written to the new path.
*
*/
saveValue: function(parentPath, key) {
return new Promise(function(resolve, reject) {
var path = null;
if (!this.app) {
reject(new Error('No app configured!'));
}
if (key) {
path = parentPath + '/' + key;
resolve(this._setFirebaseValue(path, this.data));
} else {
path = firebase.database(this.app).ref(parentPath)
.push(this.data, function(error) {
if (error) {
reject(error);
return;
}
resolve();
}).path.toString();
}
this.path = path;
}.bind(this));
},
reset: function() {
this.path = null;
return Promise.resolve();
},
destroy: function() {
return this._setFirebaseValue(this.path, null).then(function() {
return this.reset();
}.bind(this));
},
memoryPathToStoragePath: function(path) {
var storagePath = this.path;
if (path !== 'data') {
storagePath += path.replace(/^data\.?/, '/').split('.').join('/');
}
return storagePath;
},
storagePathToMemoryPath: function(storagePath) {
var path = 'data';
storagePath =
storagePath.replace(this.path, '').split('/').join('.');
if (storagePath) {
path += '.' + storagePath;
}
return path;
},
getStoredValue: function(path) {
return new Promise(function(resolve, reject) {
this.db.ref(path).once('value', function(snapshot) {
var value = snapshot.val();
if (value == null) {
resolve(this.zeroValue);
}
resolve(value);
}, this.__onError, this);
}.bind(this));
},
setStoredValue: function(path, value) {
return this._setFirebaseValue(path, value);
},
__refChanged: function(ref, oldRef) {
if (oldRef) {
oldRef.off('value', this.__onFirebaseValue, this);
}
if (ref) {
ref.on('value', this.__onFirebaseValue, this.__onError, this);
}
},
__onFirebaseValue: function(snapshot) {
var value = snapshot.val();
var exists = true;
if (value == null) {
value = this.zeroValue;
this.__needSetData = true;
exists = false;
}
if (!this.isNew) {
this.async(function() {
this.syncToMemory(function() {
this._log('Updating data from Firebase value:', value);
// set the value if:
// it is the first time we run this (or the path has changed and we are back with zeroValue)
// or if this.data does not exist
// or value is primitive
// or if firebase value obj contain less keys than this.data (https://github.com/Polymer/polymer/issues/2565)
if (this.__needSetData || !this.data || typeof value !== 'object' || ( Object.keys(value).length < Object.keys(this.data).length)) {
this.__needSetData = false;
return this.set('data', value);
}
// now, we loop over keys
for (var prop in value) {
if(value[prop] !== this.data[prop]) {
this.set(['data', prop], value[prop]);
}
}
});
this._setExists(exists);
if(!exists) {
this.fire('empty-result');
}
});
}
}
});
</script>