forked from FirebaseExtended/angularfire
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
513 lines (465 loc) · 18.1 KB
/
utils.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
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
(function() {
'use strict';
angular.module('firebase')
.factory('$firebaseConfig', ["$firebaseArray", "$firebaseObject", "$injector",
function($firebaseArray, $firebaseObject, $injector) {
return function(configOpts) {
// make a copy we can modify
var opts = angular.extend({}, configOpts);
// look up factories if passed as string names
if( typeof opts.objectFactory === 'string' ) {
opts.objectFactory = $injector.get(opts.objectFactory);
}
if( typeof opts.arrayFactory === 'string' ) {
opts.arrayFactory = $injector.get(opts.arrayFactory);
}
// extend defaults and return
return angular.extend({
arrayFactory: $firebaseArray,
objectFactory: $firebaseObject
}, opts);
};
}
])
.factory('$firebaseUtils', ["$q", "$timeout", "firebaseBatchDelay",
function($q, $timeout, firebaseBatchDelay) {
// ES6 style promises polyfill for angular 1.2.x
// Copied from angular 1.3.x implementation: https://github.com/angular/angular.js/blob/v1.3.5/src/ng/q.js#L539
function Q(resolver) {
if (!angular.isFunction(resolver)) {
throw new Error('missing resolver function');
}
var deferred = $q.defer();
function resolveFn(value) {
deferred.resolve(value);
}
function rejectFn(reason) {
deferred.reject(reason);
}
resolver(resolveFn, rejectFn);
return deferred.promise;
}
var utils = {
/**
* Returns a function which, each time it is invoked, will pause for `wait`
* milliseconds before invoking the original `fn` instance. If another
* request is received in that time, it resets `wait` up until `maxWait` is
* reached.
*
* Unlike a debounce function, once wait is received, all items that have been
* queued will be invoked (not just once per execution). It is acceptable to use 0,
* which means to batch all synchronously queued items.
*
* The batch function actually returns a wrap function that should be called on each
* method that is to be batched.
*
* <pre><code>
* var total = 0;
* var batchWrapper = batch(10, 100);
* var fn1 = batchWrapper(function(x) { return total += x; });
* var fn2 = batchWrapper(function() { console.log(total); });
* fn1(10);
* fn2();
* fn1(10);
* fn2();
* console.log(total); // 0 (nothing invoked yet)
* // after 10ms will log "10" and then "20"
* </code></pre>
*
* @param {int} wait number of milliseconds to pause before sending out after each invocation
* @param {int} maxWait max milliseconds to wait before sending out, defaults to wait * 10 or 100
* @returns {Function}
*/
batch: function(wait, maxWait) {
wait = typeof('wait') === 'number'? wait : firebaseBatchDelay;
if( !maxWait ) { maxWait = wait*10 || 100; }
var queue = [];
var start;
var cancelTimer;
var runScheduledForNextTick;
// returns `fn` wrapped in a function that queues up each call event to be
// invoked later inside fo runNow()
function createBatchFn(fn, context) {
if( typeof(fn) !== 'function' ) {
throw new Error('Must provide a function to be batched. Got '+fn);
}
return function() {
var args = Array.prototype.slice.call(arguments, 0);
queue.push([fn, context, args]);
resetTimer();
};
}
// clears the current wait timer and creates a new one
// however, if maxWait is exceeded, calls runNow() on the next tick.
function resetTimer() {
if( cancelTimer ) {
cancelTimer();
cancelTimer = null;
}
if( start && Date.now() - start > maxWait ) {
if(!runScheduledForNextTick){
runScheduledForNextTick = true;
utils.compile(runNow);
}
}
else {
if( !start ) { start = Date.now(); }
cancelTimer = utils.wait(runNow, wait);
}
}
// Clears the queue and invokes all of the functions awaiting notification
function runNow() {
cancelTimer = null;
start = null;
runScheduledForNextTick = false;
var copyList = queue.slice(0);
queue = [];
angular.forEach(copyList, function(parts) {
parts[0].apply(parts[1], parts[2]);
});
}
return createBatchFn;
},
/**
* A rudimentary debounce method
* @param {function} fn the function to debounce
* @param {object} [ctx] the `this` context to set in fn
* @param {int} wait number of milliseconds to pause before sending out after each invocation
* @param {int} [maxWait] max milliseconds to wait before sending out, defaults to wait * 10 or 100
*/
debounce: function(fn, ctx, wait, maxWait) {
var start, cancelTimer, args, runScheduledForNextTick;
if( typeof(ctx) === 'number' ) {
maxWait = wait;
wait = ctx;
ctx = null;
}
if( typeof wait !== 'number' ) {
throw new Error('Must provide a valid integer for wait. Try 0 for a default');
}
if( typeof(fn) !== 'function' ) {
throw new Error('Must provide a valid function to debounce');
}
if( !maxWait ) { maxWait = wait*10 || 100; }
// clears the current wait timer and creates a new one
// however, if maxWait is exceeded, calls runNow() on the next tick.
function resetTimer() {
if( cancelTimer ) {
cancelTimer();
cancelTimer = null;
}
if( start && Date.now() - start > maxWait ) {
if(!runScheduledForNextTick){
runScheduledForNextTick = true;
utils.compile(runNow);
}
}
else {
if( !start ) { start = Date.now(); }
cancelTimer = utils.wait(runNow, wait);
}
}
// Clears the queue and invokes the debounced function with the most recent arguments
function runNow() {
cancelTimer = null;
start = null;
runScheduledForNextTick = false;
fn.apply(ctx, args);
}
function debounced() {
args = Array.prototype.slice.call(arguments, 0);
resetTimer();
}
debounced.running = function() {
return start > 0;
};
return debounced;
},
assertValidRef: function(ref, msg) {
if( !angular.isObject(ref) ||
typeof(ref.ref) !== 'function' ||
typeof(ref.ref().transaction) !== 'function' ) {
throw new Error(msg || 'Invalid Firebase reference');
}
},
// http://stackoverflow.com/questions/7509831/alternative-for-the-deprecated-proto
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
inherit: function(ChildClass, ParentClass, methods) {
var childMethods = ChildClass.prototype;
ChildClass.prototype = Object.create(ParentClass.prototype);
ChildClass.prototype.constructor = ChildClass; // restoring proper constructor for child class
angular.forEach(Object.keys(childMethods), function(k) {
ChildClass.prototype[k] = childMethods[k];
});
if( angular.isObject(methods) ) {
angular.extend(ChildClass.prototype, methods);
}
return ChildClass;
},
getPrototypeMethods: function(inst, iterator, context) {
var methods = {};
var objProto = Object.getPrototypeOf({});
var proto = angular.isFunction(inst) && angular.isObject(inst.prototype)?
inst.prototype : Object.getPrototypeOf(inst);
while(proto && proto !== objProto) {
for (var key in proto) {
// we only invoke each key once; if a super is overridden it's skipped here
if (proto.hasOwnProperty(key) && !methods.hasOwnProperty(key)) {
methods[key] = true;
iterator.call(context, proto[key], key, proto);
}
}
proto = Object.getPrototypeOf(proto);
}
},
getPublicMethods: function(inst, iterator, context) {
utils.getPrototypeMethods(inst, function(m, k) {
if( typeof(m) === 'function' && k.charAt(0) !== '_' ) {
iterator.call(context, m, k);
}
});
},
defer: $q.defer,
reject: $q.reject,
resolve: $q.when,
//TODO: Remove false branch and use only angular implementation when we drop angular 1.2.x support.
promise: angular.isFunction($q) ? $q : Q,
makeNodeResolver:function(deferred){
return function(err,result){
if(err === null){
if(arguments.length > 2){
result = Array.prototype.slice.call(arguments,1);
}
deferred.resolve(result);
}
else {
deferred.reject(err);
}
};
},
wait: function(fn, wait) {
var to = $timeout(fn, wait||0);
return function() {
if( to ) {
$timeout.cancel(to);
to = null;
}
};
},
compile: function(fn) {
return $timeout(fn||function() {});
},
deepCopy: function(obj) {
if( !angular.isObject(obj) ) { return obj; }
var newCopy = angular.isArray(obj) ? obj.slice() : angular.extend({}, obj);
for (var key in newCopy) {
if (newCopy.hasOwnProperty(key)) {
if (angular.isObject(newCopy[key])) {
newCopy[key] = utils.deepCopy(newCopy[key]);
}
}
}
return newCopy;
},
trimKeys: function(dest, source) {
utils.each(dest, function(v,k) {
if( !source.hasOwnProperty(k) ) {
delete dest[k];
}
});
},
scopeData: function(dataOrRec) {
var data = {
$id: dataOrRec.$id,
$priority: dataOrRec.$priority
};
var hasPublicProp = false;
utils.each(dataOrRec, function(v,k) {
hasPublicProp = true;
data[k] = utils.deepCopy(v);
});
if(!hasPublicProp && dataOrRec.hasOwnProperty('$value')){
data.$value = dataOrRec.$value;
}
return data;
},
updateRec: function(rec, snap) {
var data = snap.val();
var oldData = angular.extend({}, rec);
// deal with primitives
if( !angular.isObject(data) ) {
rec.$value = data;
data = {};
}
else {
delete rec.$value;
}
// apply changes: remove old keys, insert new data, set priority
utils.trimKeys(rec, data);
angular.extend(rec, data);
rec.$priority = snap.getPriority();
return !angular.equals(oldData, rec) ||
oldData.$value !== rec.$value ||
oldData.$priority !== rec.$priority;
},
applyDefaults: function(rec, defaults) {
if( angular.isObject(defaults) ) {
angular.forEach(defaults, function(v,k) {
if( !rec.hasOwnProperty(k) ) {
rec[k] = v;
}
});
}
return rec;
},
dataKeys: function(obj) {
var out = [];
utils.each(obj, function(v,k) {
out.push(k);
});
return out;
},
each: function(obj, iterator, context) {
if(angular.isObject(obj)) {
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
var c = k.charAt(0);
if( c !== '_' && c !== '$' && c !== '.' ) {
iterator.call(context, obj[k], k, obj);
}
}
}
}
else if(angular.isArray(obj)) {
for(var i = 0, len = obj.length; i < len; i++) {
iterator.call(context, obj[i], i, obj);
}
}
return obj;
},
/**
* A utility for retrieving a Firebase reference or DataSnapshot's
* key name. This is backwards-compatible with `name()` from Firebase
* 1.x.x and `key()` from Firebase 2.0.0+. Once support for Firebase
* 1.x.x is dropped in AngularFire, this helper can be removed.
*/
getKey: function(refOrSnapshot) {
return (typeof refOrSnapshot.key === 'function') ? refOrSnapshot.key() : refOrSnapshot.name();
},
/**
* A utility for converting records to JSON objects
* which we can save into Firebase. It asserts valid
* keys and strips off any items prefixed with $.
*
* If the rec passed into this method has a toJSON()
* method, that will be used in place of the custom
* functionality here.
*
* @param rec
* @returns {*}
*/
toJSON: function(rec) {
var dat;
if( !angular.isObject(rec) ) {
rec = {$value: rec};
}
if (angular.isFunction(rec.toJSON)) {
dat = rec.toJSON();
}
else {
dat = {};
utils.each(rec, function (v, k) {
dat[k] = stripDollarPrefixedKeys(v);
});
}
if( angular.isDefined(rec.$value) && Object.keys(dat).length === 0 && rec.$value !== null ) {
dat['.value'] = rec.$value;
}
if( angular.isDefined(rec.$priority) && Object.keys(dat).length > 0 && rec.$priority !== null ) {
dat['.priority'] = rec.$priority;
}
angular.forEach(dat, function(v,k) {
if (k.match(/[.$\[\]#\/]/) && k !== '.value' && k !== '.priority' ) {
throw new Error('Invalid key ' + k + ' (cannot contain .$[]#)');
}
else if( angular.isUndefined(v) ) {
throw new Error('Key '+k+' was undefined. Cannot pass undefined in JSON. Use null instead.');
}
});
return dat;
},
doSet: function(ref, data) {
var def = utils.defer();
if( angular.isFunction(ref.set) || !angular.isObject(data) ) {
// this is not a query, just do a flat set
ref.set(data, utils.makeNodeResolver(def));
}
else {
var dataCopy = angular.extend({}, data);
// this is a query, so we will replace all the elements
// of this query with the value provided, but not blow away
// the entire Firebase path
ref.once('value', function(snap) {
snap.forEach(function(ss) {
if( !dataCopy.hasOwnProperty(utils.getKey(ss)) ) {
dataCopy[utils.getKey(ss)] = null;
}
});
ref.ref().update(dataCopy, utils.makeNodeResolver(def));
}, function(err) {
def.reject(err);
});
}
return def.promise;
},
doRemove: function(ref) {
var def = utils.defer();
if( angular.isFunction(ref.remove) ) {
// ref is not a query, just do a flat remove
ref.remove(utils.makeNodeResolver(def));
}
else {
// ref is a query so let's only remove the
// items in the query and not the entire path
ref.once('value', function(snap) {
var promises = [];
snap.forEach(function(ss) {
var d = utils.defer();
promises.push(d.promise);
ss.ref().remove(utils.makeNodeResolver(def));
});
utils.allPromises(promises)
.then(function() {
def.resolve(ref);
},
function(err){
def.reject(err);
}
);
}, function(err) {
def.reject(err);
});
}
return def.promise;
},
/**
* AngularFire version number.
*/
VERSION: '0.0.0',
batchDelay: firebaseBatchDelay,
allPromises: $q.all.bind($q)
};
return utils;
}
]);
function stripDollarPrefixedKeys(data) {
if( !angular.isObject(data) ) { return data; }
var out = angular.isArray(data)? [] : {};
angular.forEach(data, function(v,k) {
if(typeof k !== 'string' || k.charAt(0) !== '$') {
out[k] = stripDollarPrefixedKeys(v);
}
});
return out;
}
})();