-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathindexeddb.js
More file actions
731 lines (715 loc) · 27.8 KB
/
indexeddb.js
File metadata and controls
731 lines (715 loc) · 27.8 KB
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
/**
* @license $indexedDBProvider
* (c) 2013 Clemens Capitain (webcss)
* License: MIT
*/
'use strict';
/** unify browser specific implementations */
var indexedDB = window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB;
var IDBKeyRange=window.IDBKeyRange||window.mozIDBKeyRange||window.webkitIDBKeyRange||window.msIDBKeyRange;
angular.module('xc.indexedDB', []).provider('$indexedDB', function() {
var module = this,
/** IDBTransaction mode constants */
READONLY = "readonly",
READWRITE = "readwrite",
VERSIONCHANGE = "versionchange",
/** IDBCursor direction and skip behaviour constants */
NEXT = "next",
NEXTUNIQUE = "nextunique",
PREV = "prev",
PREVUNIQUE = "prevunique";
/** predefined variables */
module.dbName = '';
module.dbVersion = 1;
module.db = null;
module.dbPromise = null;
/** predefined callback functions, can be customized in angular.config */
module.onTransactionComplete = function(e) {
console.log('Transaction completed.');
};
module.onTransactionAbort = function(e) {
console.log('Transaction aborted: '+ (e.target.webkitErrorMessage || e.target.error.message || e.target.errorCode));
};
module.onTransactionError = function(e) {
console.log('Transaction failed: ' + e.target.errorCode);
};
module.onDatabaseError = function(e) {
alert("Database error: " + (e.target.webkitErrorMessage || e.target.errorCode));
};
module.onDatabaseBlocked = function(e) {
// If some other tab is loaded with the database, then it needs to be closed
// before we can proceed.
alert("Database is blocked. Try close other tabs with this page open and reload this page!");
};
/**
* @ngdoc function
* @name $indexedDBProvider.connection
* @function
*
* @description
* sets the name of the database to use
*
* @param {string} databaseName database name.
* @returns {object} this
*/
module.connection = function(databaseName) {
module.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
*/
module.upgradeDatabase = function(newVersion, callback) {
module.dbVersion = newVersion;
module.upgradeCallback = callback;
return this;
};
module.$get = ['$q', '$rootScope', function($q, $rootScope) {
/**
* @ngdoc object
* @name defaultQueryOptions
* @function
*
* @description optionally specify for cursor requests:
* - which index to use
* - a keyRange to apply
* - the direction of traversal (bottom to top/top to bottom)
*/
var defaultQueryOptions = {
useIndex: undefined,
keyRange: null,
direction: NEXT
};
/**
* @ngdoc object
* @name dbPromise
* @function
*
* @description open the database specified in $indexedDBProvider.connection and
* $indexdDBProvider.upgradeDatabase and returns a promise for this connection
* @params
* @returns {object} promise $q.promise to fullfill connection
*/
var dbPromise = function() {
var dbReq, deferred;
if (!module.dbPromise) {
deferred = $q.defer();
module.dbPromise = deferred.promise;
dbReq = indexedDB.open(module.dbName, module.dbVersion || 1);
dbReq.onsuccess = function(e) {
module.db = dbReq.result;
$rootScope.$apply(function(){
deferred.resolve(module.db);
});
};
dbReq.onblocked = module.onDatabaseBlocked;
dbReq.onerror = module.onDatabaseError;
dbReq.onupgradeneeded = function(e) {
var db = e.target.result, tx = e.target.transaction;
console.log('upgrading database "' + db.name + '" from version ' + e.oldVersion+
' to version ' + e.newVersion + '...');
module.upgradeCallback && module.upgradeCallback(e, db, tx);
};
}
return module.dbPromise;
};
/**
* @ngdoc object
* @name ObjectStore
* @function
*
* @description wrapper for IDBObjectStore
*
* @params {string} storeName name of the objectstore
*/
var ObjectStore = function(storeName) {
this.storeName = storeName;
this.transaction = undefined;
};
ObjectStore.prototype = {
/**
* @ngdoc method
* @name ObjectStore.internalObjectStore
* @function
*
* @description used internally to retrieve an objectstore
* with the correct transaction mode
*
* @params {string} storeName name of the objectstore
* @params {string} mode transaction mode to use for operation
* @returns {object} IDBObjectStore the objectstore in question
*/
internalObjectStore: function(storeName, mode) {
var me = this;
return dbPromise().then(function(db){
me.transaction = db.transaction([storeName], mode || READONLY);
me.transaction.oncomplete = module.onTransactionComplete;
me.transaction.onabort = module.onTransactionAbort;
me.onerror = module.onTransactionError;
return me.transaction.objectStore(storeName);
});
},
/**
* @ngdoc method
* @name ObjectStore.abort
* @function
*
* @description abort the current transaction
*/
"abort": function() {
if (this.transaction) {
this.transaction.abort();
}
},
/**
* @ngdoc method
* @name ObjectStore.insert
* @function
*
* @description wrapper for IDBObjectStore.add.
* input data can be a single object or an array of objects for
* bulk insertions within a single transaction
*
* @params {object or array} data the data to insert
* @returns {object} $q.promise a promise on successfull execution
*/
"insert": function(data){
var d = $q.defer();
return this.internalObjectStore(this.storeName, READWRITE).then(function(store){
var req;
if (angular.isArray(data)) {
data.forEach(function(item, i){
req = store.add(item);
req.onnotify = function(e) {
$rootScope.$apply(function(){
d.notify(e.target.result);
});
}
req.onerror = function(e) {
$rootScope.$apply(function(){
d.reject(e.target.result);
});
};
req.onsuccess = function(e) {
if(i == data.length - 1) {
$rootScope.$apply(function(){
d.resolve(e.target.result);
});
}
};
});
} else {
req = store.add(data);
req.onsuccess = req.onerror = function(e) {
$rootScope.$apply(function(){
d.resolve(e.target.result);
});
};
}
return d.promise;
});
},
/**
* @ngdoc method
* @name ObjectStore.upsert
* @function
*
* @description wrapper for IDBObjectStore.put.
* modifies existing values or inserts as new value if nonexistant
* input data can be a single object or an array of objects for
* bulk updates/insertions within a single transaction
*
* @params {object or array} data the data to upsert
* @returns {object} $q.promise a promise on successfull execution
*/
"upsert": function(data){
var d = $q.defer();
return this.internalObjectStore(this.storeName, READWRITE).then(function(store){
var req;
if (angular.isArray(data)) {
data.forEach(function(item, i){
req = store.put(item);
req.onnotify = function(e) {
$rootScope.$apply(function(){
d.notify(e.target.result);
});
}
req.onerror = function(e) {
$rootScope.$apply(function(){
d.reject(e.target.result);
});
};
req.onsuccess = function(e) {
if(i == data.length - 1) {
$rootScope.$apply(function(){
d.resolve(e.target.result);
});
}
};
});
} else {
req = store.put(data);
req.onsuccess = req.onerror = function(e) {
$rootScope.$apply(function(){
d.resolve(e.target.result);
});
};
}
return d.promise;
});
},
/**
* @ngdoc method
* @name ObjectStore.delete
* @function
*
* @description wrapper for IDBObjectStore.delete.
* deletes the value for the specified primary key
*
* @params {any value} key primary key to indetify a value
* @returns {object} $q.promise a promise on successfull execution
*/
"delete": function(key) {
var d = $q.defer();
return this.internalObjectStore(this.storeName, READWRITE).then(function(store){
var req = store.delete(key);
req.onsuccess = req.onerror = function(e) {
$rootScope.$apply(function(){
d.resolve(e.target.result);
});
};
return d.promise;
});
},
/**
* @ngdoc method
* @name ObjectStore.clear
* @function
*
* @description wrapper for IDBObjectStore.clear.
* removes all data in an objectstore
*
* @returns {object} $q.promise a promise on successfull execution
*/
"clear": function() {
var d = $q.defer();
return this.internalObjectStore(this.storeName, READWRITE).then(function(store){
var req = store.clear();
req.onsuccess = req.onerror = function(e) {
$rootScope.$apply(function(){
d.resolve(e.target.result);
});
};
return d.promise;
});
},
/**
* @ngdoc method
* @name ObjectStore.count
* @function
*
* @description wrapper for IDBObjectStore.count.
* returns the number of values in the objectstore, as a promise
*
* @returns {object} $q.promise a promise on successfull execution
*/
"count": function() {
return this.internalObjectStore(this.storeName, READONLY).then(function(store){
return store.count();
});
},
/**
* @ngdoc method
* @name ObjectStore.find
* @function
*
* @description wrapper for IDBObjectStore.get and IDBIndex.get.
* retrieves a single value with specified key, or index-key
*
* @params {any value} keyOrIndex the key to value, or an indexName
* @params {any value} key the key of an index (*optional*)
* @returns {any value} value ...wrapped in a promise
*/
"find": function(keyOrIndex, keyIfIndex){
var d = $q.defer();
var promise = d.promise;
return this.internalObjectStore(this.storeName, READONLY).then(function(store){
var req;
if(keyIfIndex) {
req = store.index(keyOrIndex).get(keyIfIndex);
} else {
req = store.get(keyOrIndex);
}
req.onsuccess = req.onerror = function(e) {
$rootScope.$apply(function(){
d.resolve(e.target.result);
});
};
return promise;
});
},
/**
* @ngdoc method
* @name ObjectStore.getAll
* @function
*
* @description wrapper for IDBObjectStore.getAll (or shim).
* retrieves all values from objectstore using IDBObjectStore.getAll
* or a cursor request if getAll is not implemented
*
* @returns {array} values ...wrapped in a promise
*/
"getAll": function() {
var results = [], d = $q.defer();
return this.internalObjectStore(this.storeName, READONLY).then(function(store){
var req;
if (store.getAll) {
req = store.getAll();
req.onsuccess = req.onerror = function(e) {
$rootScope.$apply(function(){
d.resolve(e.target.result);
});
};
} else {
req = store.openCursor();
req.onsuccess = function(e) {
var cursor = e.target.result;
if(cursor){
results.push(cursor.value);
cursor.continue();
} else {
$rootScope.$apply(function(){
d.resolve(results);
});
}
};
req.onerror = function(e) {
d.reject(e.target.result);
};
}
return d.promise;
});
},
/**
* @ngdoc method
* @name ObjectStore.each
* @function
*
* @description wrapper for IDBObjectStore.openCursor or IDBIndex.openCursor.
* returns an IDBCursor for further manipulation. See indexedDB documentation
* for details on this.
* https://developer.mozilla.org/en-US/docs/IndexedDB/Using_IndexedDB#Using_a_cursor
*
* @params {object} options optional query parameters, see defaultQueryOptions
* and QueryBuilder for details
* @returns {object} Array of values from store ...wrapped in a promise
*/
"each": function(options){
var results = [], d = $q.defer();
return this.internalObjectStore(this.storeName, READWRITE).then(function(store){
var req;
options = options || defaultQueryOptions;
if(options.useIndex) {
req = store.index(options.useIndex).openCursor(options.keyRange, options.direction);
} else {
req = store.openCursor(options.keyRange, options.direction);
}
req.onsuccess = req.onerror = function(e) {
var cursor = e.target.result;
if(cursor){
if(!options.filter || options.filter(cursor.value))
results.push(cursor.value);
cursor.continue();
} else {
$rootScope.$apply(function(){
d.resolve(results);
});
}
};
return d.promise;
});
}
};
/**
* @ngdoc object
* @name QueryBuilder
* @function
*
* @description utility object to easily create IDBKeyRange for cursor queries
*/
var QueryBuilder = function() {
this.result = angular.extend({}, defaultQueryOptions);
};
QueryBuilder.prototype = {
/**
* @ngdoc method
* @name QueryBuilder.$lt
* @function
*
* @description set an upper bound, e.g. A < value, excluding value
*
* @params {any value} value bound value
* @returns {object} this QueryBuilder, for chaining params
*/
"$lt": function(value) {
this.result.keyRange = IDBKeyRange.upperBound(value, true);
return this;
},
/**
* @ngdoc method
* @name QueryBuilder.$gt
* @function
*
* @description set a lower bound, e.g. A > value, excluding value
*
* @params {any value} value bound value
* @returns {object} this QueryBuilder, for chaining params
*/
"$gt": function(value) {
this.result.keyRange = IDBKeyRange.lowerBound(value, true);
return this;
},
/**
* @ngdoc method
* @name QueryBuilder.$lte
* @function
*
* @description set an upper bound, e.g. A <= value, including value
*
* @params {any value} value bound value
* @returns {object} this QueryBuilder, for chaining params
*/
"$lte": function(value) {
this.result.keyRange = IDBKeyRange.upperBound(value);
return this;
},
/**
* @ngdoc method
* @name QueryBuilder.$gte
* @function
*
* @description set an upper bound, e.g. A >= value, including value
*
* @params {any value} value bound value
* @returns {object} this QueryBuilder, for chaining params
*/
"$gte": function(value) {
this.result.keyRange = IDBKeyRange.lowerBound(value);
return this;
},
/**
* @ngdoc method
* @name QueryBuilder.$eq
* @function
*
* @description exact match, e.g. A = value
*
* @params {any value} value bound value
* @returns {object} this QueryBuilder, for chaining params
*/
"$eq": function(value) {
this.result.keyRange = IDBKeyRange.only(value);
return this;
},
/**
* @ngdoc method
* @name QueryBuilder.$between
* @function
*
* @description set an upper and lower bound, e.g. low >= value <= hi,
* optionally including value
*
* @params {any value} lowValue lower bound value
* @params {any value} hiValue upper bound value
* @params {boolean} exLow optional, exclude lower bound value
* @params {boolean} exHi optional, exclude upper bound value
* @returns {object} this QueryBuilder, for chaining params
*/
"$between": function(lowValue, hiValue, exLow, exHi) {
this.result.keyRange = IDBKeyRange.bound(lowValue,hiValue,exLow||false,exHi||false);
return this;
},
/**
* @ngdoc method
* @name QueryBuilder.$asc
* @function
*
* @description set the direction of traversal to ascending (natural)
*
* @params {boolean} unique return only distinct values, skipping
* duplicates (*optional*)
* @returns {object} this QueryBuilder, for chaining params
*/
"$asc": function(unique) {
this.result.order = (unique)? NEXTUNIQUE: NEXT;
return this;
},
/**
* @ngdoc method
* @name QueryBuilder.$desc
* @function
*
* @description set the direction of traversal to descending order
*
* @params {boolean} unique return only distinct values, skipping
* duplicates (*optional*)
* @returns {object} this QueryBuilder, for chaining params
*/
"$desc": function(unique) {
this.result.order = (unique)? PREVUNIQUE: PREV;
return this;
},
/**
* @ngdoc method
* @name QueryBuilder.$index
* @function
*
* @description optionally specify an index to use
*
* @params {string} indexName index to use
* @returns {object} this QueryBuilder, for chaining params
*/
"$index": function(indexName) {
this.result.useIndex = indexName;
return this;
},
/**
* @ngdoc method
* @name QueryBuilder.$filter
* @function
*
* @description optionally specify an function to determine if the item should be included
*
* @params {function} filter filter function to use
* @returns {object} this QueryBuilder, for chaining params
*/
"$filter": function(filter) {
this.result.filter = filter;
return this;
},
/**
* @ngdoc method
* @name QueryBuilder.compile
* @function
*
* @description returns an object to be passed to ObjectStore.each
* @returns {object} queryOptions
*/
"compile": function() {
return this.result;
}
};
/**
* @ngdoc angular.$provider
* @name $indexedDB
* @function
*
* @description indexedDB provider object
*/
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
*/
"objectStore": function(storeName) {
return new ObjectStore(storeName);
},
/**
* @ngdoc method
* @name $indexedDB.dbInfo
* @function
*
* @description statistical information about the current database
* - database name and version
* - objectstores in in database with name, value count, keyPath,
* autoincrement flag and current assigned indices
*
* @returns {object} DBInfo
*/
"dbInfo": function() {
var storeNames, stores = [], tx, store;
return dbPromise().then(function(db){
storeNames = Array.prototype.slice.apply(db.objectStoreNames);
tx = db.transaction(storeNames, READONLY);
storeNames.forEach(function(storeName){
store = tx.objectStore(storeName);
stores.push({
name: storeName,
keyPath: store.keyPath,
autoIncrement: store.autoIncrement,
count: store.count(),
indices: Array.prototype.slice.apply(store.indexNames)
});
});
return {
name: db.name,
version: db.version,
objectStores: stores
};
});
},
/**
* @ngdoc method
* @name $indexedDB.close
* @function
*
* @description closes the current active database
* @returns {object} this
*/
"closeDB": function() {
dbPromise().then(function(db){
db.close();
});
module.db = null;
module.dbPromise = null;
return this;
},
/**
* @ngdoc method
* @name $indexedDB.switchDB
* @function
*
* @description closes the current active database and opens another one
*
* @params {string} databaseName the name of the database to use
* @params {number} version the version number of the database
* @params {Function} upgradeCallBack the callback which proceeds the upgrade
* @returns {object} this
*/
"switchDB": function(databaseName, version, upgradeCallback) {
this.closeDB();
module.dbName = databaseName;
module.dbVersion = version || 1;
module.upgradeCallback = upgradeCallback || function() {};
return this;
},
/**
* @ngdoc method
* @name $indexedDB.queryBuilder
* @function
*
* @description provides access to the QueryBuilder utility
*
* @returns {object} QueryBuilder
*/
"queryBuilder": function() {
return new QueryBuilder();
}
};
}];
});