forked from webcss/angular-indexedDB
-
Notifications
You must be signed in to change notification settings - Fork 49
/
angular-indexed-db.js
847 lines (740 loc) · 27.2 KB
/
angular-indexed-db.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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
/**
@license $indexedDBProvider
(c) 2014 Bram Whillock (bramski)
Forked from original work by clements Capitan (webcss)
License: MIT
*/
(function() {
'use strict';
var __slice = [].slice;
angular.module('indexedDB', []).provider('$indexedDB', function() {
var IDBKeyRange, allTransactions, apiDirection, appendResultsToPromise, applyNeededUpgrades, cursorDirection, db, dbMode, dbName, dbPromise, dbVersion, defaultQueryOptions, errorMessageFor, indexedDB, readyState, upgradesByVersion;
indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
IDBKeyRange = window.IDBKeyRange || window.mozIDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
dbMode = {
readonly: "readonly",
readwrite: "readwrite"
};
readyState = {
pending: "pending"
};
cursorDirection = {
next: "next",
nextunique: "nextunique",
prev: "prev",
prevunique: "prevunique"
};
apiDirection = {
ascending: cursorDirection.next,
descending: cursorDirection.prev
};
dbName = '';
dbVersion = 1;
db = null;
upgradesByVersion = {};
dbPromise = null;
allTransactions = [];
defaultQueryOptions = {
useIndex: void 0,
keyRange: null,
direction: cursorDirection.next
};
applyNeededUpgrades = function(oldVersion, event, db, tx, $log) {
var version;
for (version in upgradesByVersion) {
if (!upgradesByVersion.hasOwnProperty(version) || version <= oldVersion) {
continue;
}
$log.log("$indexedDB: Running upgrade : " + version + " from " + oldVersion);
upgradesByVersion[version](event, db, tx);
}
};
errorMessageFor = function(e) {
if (e.target.readyState === readyState.pending) {
return "Error: Operation pending";
} else {
return e.target.webkitErrorMessage || e.target.error.message || e.target.error.name || e.target.errorCode;
}
};
appendResultsToPromise = function(promise, results) {
if (results !== void 0) {
return promise.then(function() {
return results;
});
} else {
return promise;
}
};
/**
@ngdoc function
@name $indexedDBProvider.connection
@function
@description
sets the name of the database to use
@param {string} databaseName database name.
@returns {object} this
*/
this.connection = function(databaseName) {
dbName = databaseName;
return this;
};
/**
@ngdoc function
@name $indexedDBProvider.upgradeDatabase
@function
@description provides version number and steps to upgrade the database wrapped in a
callback function
@param {number} newVersion new version number for the database.
@param {function} callback the callback which proceeds the upgrade
@returns {object} this
*/
this.upgradeDatabase = function(newVersion, callback) {
upgradesByVersion[newVersion] = callback;
dbVersion = Math.max.apply(null, Object.keys(upgradesByVersion));
return this;
};
this.$get = [
'$q', '$rootScope', '$log', function($q, $rootScope, $log) {
var DbQ, ObjectStore, Query, Transaction, addTransaction, closeDatabase, createDatabaseConnection, keyRangeForOptions, openDatabase, openTransaction, rejectWithError, validateStoreNames;
rejectWithError = function(deferred) {
return function(error) {
return $rootScope.$apply(function() {
return deferred.reject(errorMessageFor(error));
});
};
};
createDatabaseConnection = function() {
var dbReq, deferred;
deferred = $q.defer();
dbReq = indexedDB.open(dbName, parseInt(dbVersion) || 1);
dbReq.onsuccess = function() {
db = dbReq.result;
$rootScope.$apply(function() {
deferred.resolve(db);
});
};
dbReq.onblocked = dbReq.onerror = rejectWithError(deferred);
dbReq.onupgradeneeded = function(event) {
var oldVer, tx;
oldVer = event.oldVersion;
if (oldVer > Math.pow(2, 62)) {
oldVer = 0;
}
db = event.target.result;
tx = event.target.transaction;
$log.log("$indexedDB: Upgrading database '" + db.name + "' from version " + oldVer + " to version " + event.newVersion + " ...");
applyNeededUpgrades(oldVer, event, db, tx, $log);
};
return deferred.promise;
};
openDatabase = function() {
return dbPromise || (dbPromise = createDatabaseConnection());
};
closeDatabase = function() {
return openDatabase().then(function() {
db.close();
db = null;
return dbPromise = null;
});
};
validateStoreNames = function(storeNames) {
var found, storeName, _i, _len;
found = true;
for (_i = 0, _len = storeNames.length; _i < _len; _i++) {
storeName = storeNames[_i];
found = found & db.objectStoreNames.contains(storeName);
}
return found;
};
openTransaction = function(storeNames, mode) {
if (mode == null) {
mode = dbMode.readonly;
}
return openDatabase().then(function() {
if (!validateStoreNames(storeNames)) {
return $q.reject("Object stores " + storeNames + " do not exist.");
}
return new Transaction(storeNames, mode);
});
};
keyRangeForOptions = function(options) {
if (options.beginKey && options.endKey) {
return IDBKeyRange.bound(options.beginKey, options.endKey);
}
};
addTransaction = function(transaction) {
allTransactions.push(transaction.promise);
return transaction.promise["finally"](function() {
var index;
index = allTransactions.indexOf(transaction.promise);
if (index > -1) {
return allTransactions.splice(index, 1);
}
});
};
Transaction = (function() {
function Transaction(storeNames, mode) {
if (mode == null) {
mode = dbMode.readonly;
}
this.transaction = db.transaction(storeNames, mode);
this.defer = $q.defer();
this.promise = this.defer.promise;
this.setupCallbacks();
}
Transaction.prototype.setupCallbacks = function() {
this.transaction.oncomplete = (function(_this) {
return function() {
return $rootScope.$apply(function() {
return _this.defer.resolve("Transaction Completed");
});
};
})(this);
this.transaction.onabort = (function(_this) {
return function(error) {
return $rootScope.$apply(function() {
return _this.defer.reject({
title: "Transaction Aborted",
error: error
});
});
};
})(this);
this.transaction.onerror = (function(_this) {
return function(error) {
return $rootScope.$apply(function() {
return _this.defer.reject({
title: "Transaction Error",
error: error
});
});
};
})(this);
return addTransaction(this);
};
Transaction.prototype.objectStore = function(storeName) {
return this.transaction.objectStore(storeName);
};
Transaction.prototype.abort = function() {
return this.transaction.abort();
};
return Transaction;
})();
DbQ = (function() {
function DbQ() {
this.q = $q.defer();
this.promise = this.q.promise;
}
DbQ.prototype.reject = function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return $rootScope.$apply((function(_this) {
return function() {
var _ref;
return (_ref = _this.q).reject.apply(_ref, args);
};
})(this));
};
DbQ.prototype.rejectWith = function(req) {
return req.onerror = req.onblocked = (function(_this) {
return function(e) {
return _this.reject(errorMessageFor(e));
};
})(this);
};
DbQ.prototype.resolve = function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return $rootScope.$apply((function(_this) {
return function() {
var _ref;
return (_ref = _this.q).resolve.apply(_ref, args);
};
})(this));
};
DbQ.prototype.notify = function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return $rootScope.$apply((function(_this) {
return function() {
var _ref;
return (_ref = _this.q).notify.apply(_ref, args);
};
})(this));
};
DbQ.prototype.dbErrorFunction = function() {
return (function(_this) {
return function(error) {
return $rootScope.$apply(function() {
return _this.q.reject(errorMessageFor(error));
});
};
})(this);
};
DbQ.prototype.resolveWith = function(req) {
this.rejectWith(req);
return req.onsuccess = (function(_this) {
return function(e) {
return _this.resolve(e.target.result);
};
})(this);
};
return DbQ;
})();
ObjectStore = (function() {
function ObjectStore(storeName, transaction) {
this.storeName = storeName;
this.store = transaction.objectStore(storeName);
this.transaction = transaction;
}
ObjectStore.prototype.defer = function() {
return new DbQ();
};
ObjectStore.prototype._mapCursor = function(defer, mapFunc, req) {
var results;
if (req == null) {
req = this.store.openCursor();
}
results = [];
defer.rejectWith(req);
return req.onsuccess = function(e) {
var cursor;
if (cursor = e.target.result) {
results.push(mapFunc(cursor));
defer.notify(mapFunc(cursor));
return cursor["continue"]();
} else {
return defer.resolve(results);
}
};
};
ObjectStore.prototype._arrayOperation = function(data, mapFunc) {
var defer, item, req, results, _i, _len;
defer = this.defer();
if (!angular.isArray(data)) {
data = [data];
}
for (_i = 0, _len = data.length; _i < _len; _i++) {
item = data[_i];
req = mapFunc(item);
results = [];
defer.rejectWith(req);
req.onsuccess = function(e) {
results.push(e.target.result);
defer.notify(e.target.result);
if (results.length >= data.length) {
return defer.resolve(results);
}
};
}
if (data.length === 0) {
return $q.when([]);
}
return defer.promise;
};
/**
@ngdoc function
@name $indexedDBProvider.store.getAllKeys
@function
@description
gets all the keys
@returns {Q} A promise which will result with all the keys
*/
ObjectStore.prototype.getAllKeys = function() {
var defer, req;
defer = this.defer();
if (this.store.getAllKeys) {
req = this.store.getAllKeys();
defer.resolveWith(req);
} else {
this._mapCursor(defer, function(cursor) {
return cursor.key;
});
}
return defer.promise;
};
/**
@ngdoc function
@name $indexedDBProvider.store.clear
@function
@description
clears all objects from this store
@returns {Q} A promise that this can be done successfully.
*/
ObjectStore.prototype.clear = function() {
var defer, req;
defer = this.defer();
req = this.store.clear();
defer.resolveWith(req);
return defer.promise;
};
/**
@ngdoc function
@name $indexedDBProvider.store.delete
@function
@description
Deletes the item at the key. The operation is ignored if the item does not exist.
@param {key} The key of the object to delete.
@returns {Q} A promise that this can be done successfully.
*/
ObjectStore.prototype["delete"] = function(key) {
var defer;
defer = this.defer();
defer.resolveWith(this.store["delete"](key));
return defer.promise;
};
/**
@ngdoc function
@name $indexedDBProvider.store.upsert
@function
@description
Updates the given item
@param {data} Details of the item or items to update or insert
@returns {Q} A promise that this can be done successfully.
*/
ObjectStore.prototype.upsert = function(data) {
return this._arrayOperation(data, (function(_this) {
return function(item) {
return _this.store.put(item);
};
})(this));
};
/**
@ngdoc function
@name $indexedDBProvider.store.insert
@function
@description
Updates the given item
@param {data} Details of the item or items to insert
@returns {Q} A promise that this can be done successfully.
*/
ObjectStore.prototype.insert = function(data) {
return this._arrayOperation(data, (function(_this) {
return function(item) {
return _this.store.add(item);
};
})(this));
};
/**
@ngdoc function
@name $indexedDBProvider.store.getAll
@function
@description
Fetches all items from the store
@returns {Q} A promise which resolves with copies of all items in the store
*/
ObjectStore.prototype.getAll = function() {
var defer;
defer = this.defer();
if (this.store.getAll) {
defer.resolveWith(this.store.getAll());
} else {
this._mapCursor(defer, function(cursor) {
return cursor.value;
});
}
return defer.promise;
};
ObjectStore.prototype.eachWhere = function(query) {
var defer, direction, indexName, keyRange, req;
defer = this.defer();
indexName = query.indexName;
keyRange = query.keyRange;
direction = query.direction;
req = indexName ? this.store.index(indexName).openCursor(keyRange, direction) : this.store.openCursor(keyRange, direction);
this._mapCursor(defer, (function(cursor) {
return cursor.value;
}), req);
return defer.promise;
};
ObjectStore.prototype.findWhere = function(query) {
return this.eachWhere(query);
};
/**
@ngdoc function
@name $indexedDBProvider.store.each
@function
@description
Iterates through the items in the store
@param {options.beginKey} the key to start iterating from
@param {options.endKey} the key to stop iterating at
@param {options.direction} Direction to iterate in
@returns {Q} A promise which notifies with each individual item and resolves with all of them.
*/
ObjectStore.prototype.each = function(options) {
if (options == null) {
options = {};
}
return this.eachBy(void 0, options);
};
/**
@ngdoc function
@name $indexedDBProvider.store.eachBy
@function
@description
Iterates through the items in the store using an index
@param {indexName} name of the index to use instead of the primary
@param {options.beginKey} the key to start iterating from
@param {options.endKey} the key to stop iterating at
@param {options.direction} Direction to iterate in
@returns {Q} A promise which notifies with each individual item and resolves with all of them.
*/
ObjectStore.prototype.eachBy = function(indexName, options) {
var q;
if (indexName == null) {
indexName = void 0;
}
if (options == null) {
options = {};
}
q = new Query();
q.indexName = indexName;
q.keyRange = keyRangeForOptions(options);
q.direction = options.direction || defaultQueryOptions.direction;
return this.eachWhere(q);
};
/**
@ngdoc function
@name $indexedDBProvider.store.count
@function
@description
Returns a count of the items in the store
@returns {Q} A promise which resolves with the count of all the items in the store.
*/
ObjectStore.prototype.count = function() {
var defer;
defer = this.defer();
defer.resolveWith(this.store.count());
return defer.promise;
};
/**
@ngdoc function
@name $indexedDBProvider.store.find
@function
@description
Fetches an item from the store
@returns {Q} A promise which resolves with the item from the store
*/
ObjectStore.prototype.find = function(key) {
var defer, req;
defer = this.defer();
req = this.store.get(key);
defer.rejectWith(req);
req.onsuccess = (function(_this) {
return function(e) {
if (e.target.result) {
return defer.resolve(e.target.result);
} else {
return defer.reject("" + _this.storeName + ":" + key + " not found.");
}
};
})(this);
return defer.promise;
};
/**
@ngdoc function
@name $indexedDBProvider.store.findBy
@function
@description
Fetches an item from the store using a named index.
@returns {Q} A promise which resolves with the item from the store.
*/
ObjectStore.prototype.findBy = function(index, key) {
var defer;
defer = this.defer();
defer.resolveWith(this.store.index(index).get(key));
return defer.promise;
};
ObjectStore.prototype.query = function() {
return new Query();
};
return ObjectStore;
})();
Query = (function() {
function Query() {
this.indexName = void 0;
this.keyRange = void 0;
this.direction = cursorDirection.next;
}
Query.prototype.$lt = function(value) {
this.keyRange = IDBKeyRange.upperBound(value, true);
return this;
};
Query.prototype.$gt = function(value) {
this.keyRange = IDBKeyRange.lowerBound(value, true);
return this;
};
Query.prototype.$lte = function(value) {
this.keyRange = IDBKeyRange.upperBound(value);
return this;
};
Query.prototype.$gte = function(value) {
this.keyRange = IDBKeyRange.lowerBound(value);
return this;
};
Query.prototype.$eq = function(value) {
this.keyRange = IDBKeyRange.only(value);
return this;
};
Query.prototype.$between = function(low, hi, exLow, exHi) {
if (exLow == null) {
exLow = false;
}
if (exHi == null) {
exHi = false;
}
this.keyRange = IDBKeyRange.bound(low, hi, exLow, exHi);
return this;
};
Query.prototype.$desc = function(unique) {
this.direction = unique ? cursorDirection.prevunique : cursorDirection.prev;
return this;
};
Query.prototype.$asc = function(unique) {
this.direction = unique ? cursorDirection.nextunique : cursorDirection.next;
return this;
};
Query.prototype.$index = function(indexName) {
this.indexName = indexName;
return this;
};
return Query;
})();
return {
/**
@ngdoc method
@name $indexedDB.objectStore
@function
@description an IDBObjectStore to use
@params {string} storeName the name of the objectstore to use
@returns {object} ObjectStore
*/
openStore: function(storeName, callBack, mode) {
if (mode == null) {
mode = dbMode.readwrite;
}
return openTransaction([storeName], mode).then(function(transaction) {
var results;
results = callBack(new ObjectStore(storeName, transaction));
return appendResultsToPromise(transaction.promise, results);
});
},
openStores: function(storeNames, callback, mode) {
if (mode == null) {
mode = dbMode.readwrite;
}
return openTransaction(storeNames, mode).then(function(transaction) {
var objectStores, results, storeName;
objectStores = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = storeNames.length; _i < _len; _i++) {
storeName = storeNames[_i];
_results.push(new ObjectStore(storeName, transaction));
}
return _results;
})();
results = callback.apply(null, objectStores);
return appendResultsToPromise(transaction.promise, results);
});
},
openAllStores: function(callback, mode) {
if (mode == null) {
mode = dbMode.readwrite;
}
return openDatabase().then((function(_this) {
return function() {
var objectStores, results, storeName, storeNames, transaction;
storeNames = Array.prototype.slice.apply(db.objectStoreNames);
transaction = new Transaction(storeNames, mode);
objectStores = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = storeNames.length; _i < _len; _i++) {
storeName = storeNames[_i];
_results.push(new ObjectStore(storeName, transaction));
}
return _results;
})();
results = callback.apply(null, objectStores);
return appendResultsToPromise(transaction.promise, results);
};
})(this));
},
/**
@ngdoc method
@name $indexedDB.closeDatabase
@function
@description Closes the database for use and completes all transactions.
*/
closeDatabase: function() {
return closeDatabase();
},
/**
@ngdoc method
@name $indexedDB.deleteDatabase
@function
@description Closes and then destroys the current database. Returns a promise that resolves when this is persisted.
*/
deleteDatabase: function() {
return closeDatabase().then(function() {
var defer;
defer = new DbQ();
defer.resolveWith(indexedDB.deleteDatabase(dbName));
return defer.promise;
})["finally"](function() {
return $log.log("$indexedDB: " + dbName + " database deleted.");
});
},
queryDirection: apiDirection,
flush: function() {
if (allTransactions.length > 0) {
return $q.all(allTransactions);
} else {
return $q.when([]);
}
},
/**
@ngdoc method
@name $indexedDB.databaseInfo
@function
@description Returns information about this database.
*/
databaseInfo: function() {
return openDatabase().then(function() {
var storeNames, transaction;
transaction = null;
storeNames = Array.prototype.slice.apply(db.objectStoreNames);
return openTransaction(storeNames, dbMode.readonly).then(function(transaction) {
var store, storeName, stores;
stores = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = storeNames.length; _i < _len; _i++) {
storeName = storeNames[_i];
store = transaction.objectStore(storeName);
_results.push({
name: storeName,
keyPath: store.keyPath,
autoIncrement: store.autoIncrement,
indices: Array.prototype.slice.apply(store.indexNames)
});
}
return _results;
})();
return transaction.promise.then(function() {
return {
name: db.name,
version: db.version,
objectStores: stores
};
});
});
});
}
};
}
];
});
}).call(this);
//# sourceMappingURL=angular-indexed-db.js.map