Skip to content

Commit 4c32e46

Browse files
committed
Added serialization for values in database.js
1 parent 98832e2 commit 4c32e46

File tree

1 file changed

+34
-3
lines changed

1 file changed

+34
-3
lines changed

lib/modules/database.js

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -160,21 +160,24 @@ class DatabaseRef extends ReferenceBase {
160160

161161
setAt(val) {
162162
const path = this.dbPath();
163-
return promisify('set', FirestackDatabase)(path, val)
163+
const value = this._serializeValue(val);
164+
return promisify('set', FirestackDatabase)(path, value)
164165
}
165166

166167
updateAt(val) {
167168
const path = this.dbPath();
168-
return promisify('update', FirestackDatabase)(path, val)
169+
const value = this._serializeValue(val);
170+
return promisify('update', FirestackDatabase)(path, value)
169171
}
170172

171173
removeAt(key) {
172174
const path = this.dbPath();
173175
return promisify('remove', FirestackDatabase)(path)
174176
}
175177

176-
push(value={}) {
178+
push(val={}) {
177179
const path = this.dbPath();
180+
const value = this._serializeValue(val);
178181
return promisify('push', FirestackDatabase)(path, value)
179182
.then(({ref}) => {
180183
return new DatabaseRef(this.db, ref.split(separator))
@@ -231,6 +234,34 @@ class DatabaseRef extends ReferenceBase {
231234
return Promise.all(promises);
232235
}
233236

237+
// Sanitize value
238+
// As Firebase cannot store date objects.
239+
_serializeValue(obj={}) {
240+
return Object.keys(obj).reduce((sum, key) => {
241+
let val = obj[key];
242+
if (val instanceof Date) {
243+
val = val.toISOString();
244+
}
245+
return {
246+
...sum,
247+
[key]: val
248+
}
249+
}, {});
250+
}
251+
252+
_deserializeValue(obj={}) {
253+
return Object.keys(obj).reduce((sum, key) => {
254+
let val = obj[key];
255+
if (val instanceof Date) {
256+
val = val.getTime();
257+
}
258+
return {
259+
...sum,
260+
[key]: val
261+
}
262+
}, {});
263+
}
264+
234265
// Modifiers
235266
orderByKey() {
236267
return this.query.setOrderBy('orderByKey');

0 commit comments

Comments
 (0)