-
Notifications
You must be signed in to change notification settings - Fork 86
/
angular-localForage.js
539 lines (464 loc) · 17.7 KB
/
angular-localForage.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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
(function(root, factory) {
'use strict';
var angular = (root && root.angular) || (window && window.angular);
if(typeof define === 'function' && define.amd) { // AMD
define(['localforage'], function(localforage) {
return factory(angular, localforage);
});
} else if(typeof exports === 'object' || typeof global === 'object') {
if(typeof module === 'undefined') {
global.module.exports = factory(angular, require('localforage')); // NW.js
} else {
module.exports = factory(angular, require('localforage')); // Node/Browserify
}
} else {
return factory(angular, root.localforage); // Browser
}
})(this, function(angular, localforage, undefined) {
'use strict';
var angularLocalForage = angular.module('LocalForageModule', ['ng']);
angularLocalForage.provider('$localForage', function() {
var lfInstances = {},
defaultConfig = {
name: 'lf'
},
// Send signals for each of the following actions ?
notify = {
setItem: false,
removeItem: false
},
watchers = {};
// Setter for notification config, itemSet & itemRemove should be booleans
this.setNotify = function(itemSet, itemRemove) {
notify = {
setItem: itemSet,
removeItem: itemRemove
};
};
this.config = function(config) {
if(!angular.isObject(config)) {
throw new Error('The config parameter should be an object');
}
angular.extend(defaultConfig, config);
};
this.$get = ['$rootScope', '$q', '$parse', function($rootScope, $q, $parse) {
var LocalForageInstance = function LocalForageInstance(params) {
if(angular.isDefined(params)) {
this._localforage = localforage.createInstance(params);
} else {
this._localforage = localforage;
localforage.config(defaultConfig);
}
};
LocalForageInstance.prototype.createInstance = function createInstance(config) {
if(angular.isObject(config)) { // create new instance
config = angular.extend({}, defaultConfig, config);
if(angular.isDefined(lfInstances[config.name])) {
throw new Error('A localForage instance with the name ' + config.name + ' is already defined.');
}
lfInstances[config.name] = new LocalForageInstance(config);
return lfInstances[config.name];
} else {
throw new Error('The parameter should be a config object.')
}
};
LocalForageInstance.prototype.instance = function instance(name) {
if(angular.isUndefined(name)) {
return lfInstances[defaultConfig.name];
} else if(angular.isString(name)) {
if(angular.isDefined(lfInstances[name])) {
return lfInstances[name];
} else {
throw new Error('No localForage instance of that name exists.')
}
} else {
throw new Error('The parameter should be a string.')
}
};
// Setter for the storage driver
LocalForageInstance.prototype.setDriver = function setDriver(driver) {
return this._localforage.setDriver(driver);
};
// Getter for the storage driver
LocalForageInstance.prototype.driver = function driver() {
return this._localforage.driver();
};
// Define a new driver for upstream consistency
LocalForageInstance.prototype.defineDriver = function defineDriver(driver) {
return this._localforage.defineDriver(driver);
}
// Directly adds a value to storage
LocalForageInstance.prototype.setItem = function setItem(key, value) {
// throw error on undefined key, we allow undefined value because... why not ?
if(angular.isUndefined(key)) {
throw new Error("You must define a key to set");
}
var self = this;
var args = arguments;
var localCopy;
if(angular.isArray(key)) {
if(!angular.isArray(value)) {
throw new Error('If you set an array of keys, the values should be an array too');
}
return $q.all(key.map(function (k, index) {
return self.setItem(k, value[index]);
}));
}
localCopy = stripMeta(value);
return self._localforage
.setItem(self.prefix() + key, localCopy)
.then(function success() {
if(notify.setItem) {
$rootScope.$broadcast('LocalForageModule.setItem', {
key: key,
newvalue: localCopy,
driver: self.driver()
});
}
return localCopy;
})
.catch(onError(args, self.setItem));
function stripMeta(value) {
var copy;
if (angular.isArray(value)) {
return value.map(stripMeta);
} else if (angular.isObject(value) && value.constructor === Object) {
copy = angular.extend({}, value);
angular.isDefined(copy.$promise) && delete copy.$promise;
angular.isDefined(copy.$$hashKey) && delete copy.$$hashKey;
return Object
.keys(copy)
.reduce(function stripEntries(acc, key) {
acc[key] = stripMeta(copy[key]);
return acc;
}, {});
}
return value;
}
};
// Directly get a value from storage
LocalForageInstance.prototype.getItem = function getItem(key, rejectOnNull) {
// throw error on undefined key
if(angular.isUndefined(key)) {
throw new Error("You must define a key to get");
}
var deferred = $q.defer(),
args = arguments,
self = this,
promise;
if(angular.isArray(key)) {
var res = [],
found = 0;
promise = self._localforage.iterate(function(value, k) {
var index = key.indexOf(self.prefix() + k);
if(index > -1) {
res[index] = value;
found++;
}
if(found === key.length) {
return res;
}
}).then(function() {
var shouldResolve = true;
for (var i = 0; i < key.length; i++) {
if (angular.isUndefined(res[i])) {
res[i] = null;
shouldResolve = false;
}
}
if (shouldResolve || !rejectOnNull) {
deferred.resolve(res);
} else {
deferred.reject(res);
}
});
} else {
promise = self._localforage.getItem(self.prefix() + key).then(function(item) {
if (rejectOnNull && item === null) {
deferred.reject(item);
} else {
deferred.resolve(item);
}
});
}
promise.then(null, function error(data) {
self.onError(data, args, self.getItem, deferred);
});
return deferred.promise;
};
// Iterate over all the values in storage
LocalForageInstance.prototype.iterate = function iterate(callback) {
// throw error on undefined key
if(angular.isUndefined(callback)) {
throw new Error("You must define a callback to iterate");
}
var deferred = $q.defer(),
args = arguments,
self = this;
self._localforage.iterate(callback).then(function success(item) {
deferred.resolve(item);
}, function error(data) {
self.onError(data, args, self.iterate, deferred);
});
return deferred.promise;
};
// Remove an item from storage
LocalForageInstance.prototype.removeItem = function removeItem(key) {
// throw error on undefined key
if(angular.isUndefined(key)) {
throw new Error("You must define a key to remove");
}
var self = this;
if(angular.isArray(key)) {
var promises = [];
angular.forEach(key, function(k, index) {
promises.push(self.removeItem(k));
});
return $q.all(promises);
} else {
var deferred = $q.defer(),
args = arguments;
self._localforage.removeItem(self.prefix() + key).then(function success() {
if(notify.removeItem) {
$rootScope.$broadcast('LocalForageModule.removeItem', {key: key, driver: self.driver()});
}
deferred.resolve();
}, function error(data) {
self.onError(data, args, self.removeItem, deferred);
});
return deferred.promise;
}
};
// Get an item and removes it from storage
LocalForageInstance.prototype.pull = function pull(key) {
var self = this;
var itemValue;
if(angular.isUndefined(key)) {
throw new Error("You must define a key to pull");
}
return self
.getItem(key)
.then(function (value) {
itemValue = value;
return self.removeItem(key);
})
.then(function () {
return itemValue;
});
};
// Remove all data for this app from storage
LocalForageInstance.prototype.clear = function clear() {
var deferred = $q.defer(),
args = arguments,
self = this;
self._localforage.clear().then(function success(keys) {
deferred.resolve();
}, function error(data) {
self.onError(data, args, self.clear, deferred);
});
return deferred.promise;
// return $q(function (resolve, reject) {
// self._localforage
// .clear()
// .then(function (keys) {
// resolve();
// })
// .catch(onError(arguments, self.clear));
// });
};
// Return the key for item at position n
LocalForageInstance.prototype.key = function key(n) {
// throw error on undefined n
if(angular.isUndefined(n)) {
throw new Error("You must define a position to get for the key function");
}
var deferred = $q.defer(),
args = arguments,
self = this;
self._localforage.key(n).then(function success(key) {
deferred.resolve(key);
}, function error(data) {
self.onError(data, args, self.key, deferred);
});
return deferred.promise;
};
var keys = function keys() {
var deferred = $q.defer(),
args = arguments,
self = this;
self._localforage.keys().then(function success(keyList) {
if(defaultConfig.oldPrefix && self.driver() === 'localStorageWrapper') {
var tempKeyList = [];
for(var i = 0, len = keyList.length; i < len; i++) {
tempKeyList.push(
keyList[i].substr(self.prefix().length, keyList[i].length)
);
}
keyList = tempKeyList;
}
deferred.resolve(keyList);
}, function error(data) {
self.onError(data, args, self.keys, deferred);
});
return deferred.promise;
};
// Return the list of keys stored for this application
LocalForageInstance.prototype.keys = keys;
// deprecated
LocalForageInstance.prototype.getKeys = keys;
// Returns the number of keys in this storage
LocalForageInstance.prototype.length = function() {
var deferred = $q.defer(),
args = arguments,
self = this;
self._localforage.length().then(function success(length) {
deferred.resolve(length);
}, function error(data) {
self.onError(data, args, length, deferred);
});
return deferred.promise;
};
/**
* Bind - let's you directly bind a LocalForage value to a $scope variable
* @param {Angular $scope} $scope - the current scope you want the variable available in
* @param {String/Object} opts - the key name of the variable you are binding OR an object with the key and custom options like default value or instance name
* Here are the available options you can set:
* * key: the key used in storage and in the scope (if scopeKey isn't defined)
* * defaultValue: the default value
* * name: name of the instance that should store the data
* * scopeKey: the key used in the scope
* @returns {*} - returns whatever the stored value is
*/
LocalForageInstance.prototype.bind = function bind($scope, opts) {
if(angular.isString(opts)) {
opts = {
key: opts
};
} else if(!angular.isObject(opts) || angular.isUndefined(opts.key)) {
throw new Error("You must define a key to bind");
}
var defaultOpts = {
defaultValue: '',
name: defaultConfig.name
};
// If no defined options we use defaults otherwise extend defaults
opts = angular.extend({}, defaultOpts, opts);
var self = lfInstances[opts.name];
if(angular.isUndefined(self)) {
throw new Error("You must use the name of an existing instance");
}
// Set the storeName key for the LocalForage entry
// use user defined in specified
var scopeKey = opts.scopeKey || opts.key,
model = $parse(scopeKey);
return self
.getItem(opts.key, true)
.then(function(item) {
model.assign($scope, item);
return item;
})
.catch(function () {
model.assign($scope, opts.defaultValue);
return self.setItem(opts.key, opts.defaultValue);
})
.then(function (item) {
if(angular.isDefined(watchers[opts.key])) {
watchers[opts.key]();
}
watchers[opts.key] = $scope.$watch(scopeKey, function(val) {
if(angular.isDefined(val)) {
self.setItem(opts.key, val);
}
}, true);
return item;
});
};
/**
* Unbind - let's you unbind a variable from localForage while removing the value from both
* the localForage and the local variable and sets it to null
* @param {String/Object} opts - the key name of the variable you are unbinding OR an object with the key and custom options like default value or instance name
* Here are the available options you can set:
* * key: the key used in storage and in the scope (if scopeKey isn't defined)
* * name: name of the instance that should store the data
* * scopeKey: the key used in the scope
*/
LocalForageInstance.prototype.unbind = function unbind($scope, opts) {
if(angular.isString(opts)) {
opts = {
key: opts
}
} else if(!angular.isObject(opts) || angular.isUndefined(opts.key)) {
throw new Error("You must define a key to unbind");
}
var defaultOpts = {
scopeKey: opts.key,
name: defaultConfig.name
};
// If no defined options we use defaults otherwise extend defaults
opts = angular.extend({}, defaultOpts, opts);
var self = lfInstances[opts.name];
if(angular.isUndefined(self)) {
throw new Error("You must use the name of an existing instance");
}
$parse(opts.scopeKey).assign($scope, null);
if(angular.isDefined(watchers[opts.key])) {
watchers[opts.key](); // unwatch
delete watchers[opts.key];
}
return self.removeItem(opts.key);
};
LocalForageInstance.prototype.prefix = function() {
return this.driver() === 'localStorageWrapper' && defaultConfig.oldPrefix ? this._localforage.config().name + '.' : '';
};
// Handling errors
LocalForageInstance.prototype.onError = function(err, args, fct, deferred) {
// test for private browsing errors in Firefox & Safari
if(((angular.isObject(err) && err.name ? err.name === 'InvalidStateError' : (angular.isString(err) && err === 'InvalidStateError')) && this.driver() === 'asyncStorage')
|| (angular.isObject(err) && err.code && err.code === 5)) {
var self = this;
self.setDriver('localStorageWrapper').then(function() {
fct.apply(self, args).then(function(item) {
deferred.resolve(item);
}, function(data) {
deferred.reject(data);
});
}, function() {
deferred.reject(err);
});
} else {
deferred.reject(err);
}
};
function onError(args, fct) {
return function(err) {
if(((angular.isObject(err) && err.name ? err.name === 'InvalidStateError' : (angular.isString(err) && err === 'InvalidStateError')) && this.driver() === 'asyncStorage')
|| (angular.isObject(err) && err.code && err.code === 5)) {
var self = this;
return self
.setDriver('localStorageWrapper')
.then(function () {
return fct.apply(self, args);
});
}
return $q.reject(err);
};
}
lfInstances[defaultConfig.name] = new LocalForageInstance();
return lfInstances[defaultConfig.name];
}]
});
angularLocalForage.directive('localForage', ['$localForage', function($localForage) {
return {
restrict: 'A',
link: function($scope, $element, $attrs) {
var opts = $scope.$eval($attrs.localForage);
if(angular.isObject(opts) && angular.isDefined(opts.key)) {
$localForage.bind($scope, opts);
} else {
$localForage.bind($scope, $attrs.localForage);
}
}
}
}]);
return angularLocalForage.name;
});