This repository has been archived by the owner on Mar 8, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 41
/
angular-locker.js
704 lines (627 loc) · 25 KB
/
angular-locker.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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
/**
* angular-locker
*
* A simple & configurable abstraction for local/session storage in angular projects.
*
* @link https://github.com/tymondesigns/angular-locker
* @author Sean Tymon @tymondesigns
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(function () {
return factory(root.angular || (window && window.angular));
});
} else if (typeof exports === 'object') {
module.exports = factory(root.angular || (window && window.angular));
} else {
factory(root.angular);
}
})(this, function (angular) {
'use strict';
return angular.module('angular-locker', [])
.provider('locker', function () {
/**
* If value is a function then execute, otherwise return
*
* @private
*
* @param {Mixed} value The value to execute or return
* @param {Mixed} param The parameter to pass to function if applicable
*
* @return {Mixed}
*/
var _value = function (value, param) {
return angular.isFunction(value) ? value(param) : value;
};
/**
* Determine whether a value is defined and not null
*
* @private
*
* @param {Mixed} value The value to check
*
* @return {Boolean}
*/
var _defined = function (value) {
return angular.isDefined(value) && value !== null;
};
/**
* Trigger an error
*
* @private
* @throws {Error}
*
* @param {String} msg The error message
*/
var _error = function (msg) {
throw new Error('[angular-locker] ' + msg);
};
/**
* Set the defaults
*
* @private
*
* @type {Object}
*/
var defaults = {
driver: 'local',
namespace: 'locker',
eventsEnabled: true,
separator: '.',
extend: {}
};
return {
/**
* Allow the defaults to be specified via the `lockerProvider`
*
* @param {Object} value The defaults to override
*/
defaults: function (value) {
if (! _defined(value)) return defaults;
angular.forEach(value, function (val, key) {
if (defaults.hasOwnProperty(key)) defaults[key] = val;
});
},
/**
* The locker service
*/
$get: ['$window', '$rootScope', '$parse', function ($window, $rootScope, $parse) {
/**
* Define the Locker class
*
* @public
* @constructor
*
* @param {Object} options The config options to initialize with
*/
function Locker (options) {
/**
* The config options
*
* @private
*
* @type {Object}
*/
this._options = options;
/**
* Out of the box drivers
*
* @private
*
* @type {Object}
*/
this._registeredDrivers = angular.extend({
local: $window.localStorage,
session: $window.sessionStorage
}, options.extend);
/**
* Get the Storage instance from the key
*
* @private
*
* @param {String} driver The storage driver identifier
*
* @return {Storage}
*/
this._resolveDriver = function (driver) {
if (! this._registeredDrivers.hasOwnProperty(driver)) {
_error('The driver "' + driver + '" was not found.');
}
return this._registeredDrivers[driver];
};
/**
* The driver instance
*
* @private
*
* @type {Storage}
*/
this._driver = this._resolveDriver(options.driver);
/**
* The namespace value
*
* @private
*
* @type {String}
*/
this._namespace = options.namespace;
/**
* Separates the namespace from the keys
*
* @private
*
* @type {String}
*/
this._separator = options.separator;
/**
* Store the watchers here so we can un-register them later
*
* @private
*
* @type {Object}
*/
this._watchers = {};
/**
* Check browser support
*
* @private
* @see github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js#L38-L47
*
* @param {String} driver The driver to check support with
*
* @return {Boolean}
*/
this._checkSupport = function (driver) {
if (! _defined(this._supported)) {
var l = 'l';
try {
this._resolveDriver(driver || options.driver).setItem(l, l);
this._resolveDriver(driver || options.driver).removeItem(l);
this._supported = true;
} catch (e) {
this._supported = false;
}
}
return this._supported;
};
/**
* Build the storage key from the namspace
*
* @private
*
* @param {String} key The key to build the prefix with
*
* @return {String}
*/
this._getPrefix = function (key) {
if (! this._namespace) return key;
return this._namespace + this._separator + key;
};
/**
* Try to encode value as json, or just return the value upon failure
*
* @private
*
* @param {Mixed} value The value to serialize
*
* @return {Mixed}
*/
this._serialize = function (value) {
try {
return angular.toJson(value);
} catch (e) {
return value;
}
};
/**
* Try to parse value as json, if it fails then it probably isn't json
* so just return it
*
* @private
*
* @param {String} value The value to unserialize
*
* @return {Mixed}
*/
this._unserialize = function (value) {
try {
return angular.fromJson(value);
} catch (e) {
return value;
}
};
/**
* Trigger an event
*
* @private
*
* @param {String} name The name of the event to trigger
* @param {Object} payload The data to pass along with event
*/
this._event = function (name, payload) {
if (this._options.eventsEnabled) {
$rootScope.$emit('locker.' + name, angular.extend(payload, {
driver: this._options.driver,
namespace: this._namespace,
}));
}
};
/**
* Add to storage
*
* @private
* @throws {Error} if browser support fails
*
* @param {String} key The key to add
* @param {Mixed} value The value to add
*/
this._setItem = function (key, value) {
if (! this._checkSupport()) {
_error('The browser does not support the "' + options.driver + '" driver');
}
try {
var oldVal = this._getItem(key);
this._driver.setItem(this._getPrefix(key), this._serialize(value));
if (this._exists(key) && ! angular.equals(oldVal, value)) {
this._event('item.updated', { key: key, oldValue: oldVal, newValue: value });
} else {
this._event('item.added', { key: key, value: value });
}
} catch (e) {
if (['QUOTA_EXCEEDED_ERR',
'NS_ERROR_DOM_QUOTA_REACHED',
'QuotaExceededError'].indexOf(e.name) !== -1) {
_error('The browser storage quota has been exceeded');
} else {
_error('Could not add item with key "' + key + '"');
}
}
};
/**
* Get from storage
*
* @private
* @throws {Error} if browser support fails
*
* @param {String} key The key to get
*
* @return {Mixed}
*/
this._getItem = function (key) {
if (! this._checkSupport()) {
_error('The browser does not support the "' + options.driver + '" driver');
}
return this._unserialize(this._driver.getItem(this._getPrefix(key)));
};
/**
* Exists in storage
*
* @private
* @throws {Error} if browser support fails
*
* @param {String} key The key to check for existence
*
* @return {Boolean}
*/
this._exists = function (key) {
if (! this._checkSupport()) {
_error('The browser does not support the "' + options.driver + '" driver');
}
return this._driver.hasOwnProperty(this._getPrefix(_value(key))) || !! this._getItem(key);
};
/**
* Remove from storage
*
* @private
* @throws {Error} if browser support fails
*
* @param {String} key The key to remove
*
* @return {Boolean}
*/
this._removeItem = function (key) {
if (! this._checkSupport()) {
_error('The browser does not support the "' + options.driver + '" driver');
}
if (! this._exists(key)) return false;
this._driver.removeItem(this._getPrefix(key));
this._event('item.forgotten', { key: key });
return true;
};
}
/**
* Define the public api
*
* @public
*
* @type {Object}
*/
Locker.prototype = {
/**
* Add a new item to storage (even if it already exists)
*
* @public
*
* @param {Mixed} key The key to add
* @param {Mixed} value The value to add
* @param {Mixed} def The default to pass to function if doesn't already exist
*
* @return {Locker|Boolean}
*/
put: function (key, value, def) {
if (! _defined(key)) return false;
key = _value(key);
if (angular.isObject(key)) {
angular.forEach(key, function (value, key) {
this._setItem(key, _defined(value) ? value : def);
}, this);
} else {
if (! _defined(value)) return false;
var val = this._getItem(key);
this._setItem(key, _value(value, _defined(val) ? val : def));
}
return this;
},
/**
* Add an item to storage if it doesn't already exist
*
* @public
*
* @param {Mixed} key The key to add
* @param {Mixed} value The value to add
* @param {Mixed} def The default to pass to function if doesn't already exist
*
* @return {Boolean}
*/
add: function (key, value, def) {
if (! this.has(key)) {
this.put(key, value, def);
return true;
}
return false;
},
/**
* Retrieve the specified item from storage
*
* @public
*
* @param {String|Array} key The key to get
* @param {Mixed} def The default value if it does not exist
*
* @return {Mixed}
*/
get: function (key, def) {
if (angular.isArray(key)) {
var items = {};
angular.forEach(key, function (k) {
if (this.has(k)) items[k] = this._getItem(k);
}, this);
return items;
}
if (! this.has(key)) return arguments.length === 2 ? def : void 0;
return this._getItem(key);
},
/**
* Determine whether the item exists in storage
*
* @public
*
* @param {String|Function} key - The key to remove
*
* @return {Boolean}
*/
has: function (key) {
return this._exists(key);
},
/**
* Remove specified item(s) from storage
*
* @public
*
* @param {String|Array} key The key or array of keys to remove
*
* @return {Object}
*/
forget: function (key) {
key = _value(key);
if (angular.isArray(key)) {
key.map(this._removeItem, this);
} else {
this._removeItem(key);
}
return this;
},
/**
* Retrieve the specified item from storage and then remove it
*
* @public
*
* @param {String|Array} key The key to pull from storage
* @param {Mixed} def The default value if it does not exist
*
* @return {Mixed}
*/
pull: function (key, def) {
var value = this.get(key, def);
this.forget(key);
return value;
},
/**
* Return all items in storage within the current namespace/driver
*
* @public
*
* @return {Object}
*/
all: function () {
var items = {};
angular.forEach(this._driver, function (value, key) {
if (this._namespace) {
var prefix = this._namespace + this._separator;
if (key.indexOf(prefix) === 0) key = key.substring(prefix.length);
}
if (this.has(key)) items[key] = this.get(key);
}, this);
return items;
},
/**
* Get the storage keys as an array
*
* @public
*
* @return {Array}
*/
keys: function () {
return Object.keys(this.all());
},
/**
* Remove all items set within the current namespace/driver
*
* @public
*
* @return {Locker}
*/
clean: function () {
return this.forget(this.keys());
},
/**
* Empty the current storage driver completely. careful now.
*
* @public
*
* @return {Locker}
*/
empty: function () {
this._driver.clear();
return this;
},
/**
* Get the total number of items within the current namespace
*
* @public
*
* @return {Integer}
*/
count: function () {
return this.keys().length;
},
/**
* Bind a storage key to a $scope property
*
* @public
*
* @param {Object} $scope The angular $scope object
* @param {String} key The key in storage to bind to
* @param {Mixed} def The default value to initially bind
*
* @return {Locker}
*/
bind: function ($scope, key, def) {
if (! _defined( $scope.$eval(key) )) {
$parse(key).assign($scope, this.get(key, def));
this.add(key, def);
}
var self = this;
this._watchers[key + $scope.$id] = $scope.$watch(key, function (newVal) {
self.put(key, newVal);
}, angular.isObject($scope[key]));
return this;
},
/**
* Unbind a storage key from a $scope property
*
* @public
*
* @param {Object} $scope The angular $scope object
* @param {String} key The key to remove from bindings
*
* @return {Locker}
*/
unbind: function ($scope, key) {
$parse(key).assign($scope, void 0);
this.forget(key);
var watchId = key + $scope.$id;
if (this._watchers[watchId]) {
// execute the de-registration function
this._watchers[watchId]();
delete this._watchers[watchId];
}
return this;
},
/**
* Set the storage driver on a new instance to enable overriding defaults
*
* @public
*
* @param {String} driver The driver to switch to
*
* @return {Locker}
*/
driver: function (driver) {
return this.instance(angular.extend(this._options, { driver: driver }));
},
/**
* Get the currently set driver
*
* @public
*
* @return {Storage}
*/
getDriver: function () {
return this._driver;
},
/**
* Set the namespace on a new instance to enable overriding defaults
*
* @public
*
* @param {String} namespace The namespace to switch to
*
* @return {Locker}
*/
namespace: function (namespace) {
return this.instance(angular.extend(this._options, { namespace: namespace }));
},
/**
* Get the currently set namespace
*
* @public
*
* @return {String}
*/
getNamespace: function () {
return this._namespace;
},
/**
* Check browser support
*
* @public
* @see github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js#L38-L47
*
* @param {String} driver The driver to check support with
*
* @return {Boolean}
*/
supported: function (driver) {
return this._checkSupport(driver);
},
/**
* Get a new instance of Locker
*
* @public
*
* @param {Object} options The config options to instantiate with
*
* @return {Locker}
*/
instance: function (options) {
return new Locker(options);
}
};
// return the default instance
return new Locker(defaults);
}]
};
}).name; // export module name for the likes of Browserify and Webpack
});