forked from treojs/treo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtreo.js
774 lines (654 loc) · 18.8 KB
/
treo.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
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.treo = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var parseRange = require('idb-range');
/**
* Expose `Index`.
*/
module.exports = Index;
/**
* Initialize new `Index`.
*
* @param {Store} store
* @param {String} name
* @param {String|Array} field
* @param {Object} opts { unique: false, multi: false }
*/
function Index(store, name, field, opts) {
this.store = store;
this.name = name;
this.field = field;
this.opts = opts;
this.multi = opts.multi || opts.multiEntry || false;
this.unique = opts.unique || false;
}
/**
* Get `key`.
*
* @param {Object|IDBKeyRange} key
* @param {Function} cb
*/
Index.prototype.get = function(key, cb) {
var result = [];
var isUnique = this.unique;
var opts = { range: key, iterator: iterator };
this.cursor(opts, function(err) {
if (err) return cb(err);
isUnique ? cb(null, result[0]) : cb(null, result);
});
function iterator(cursor) {
result.push(cursor.value);
cursor.continue();
}
};
/**
* Count records by `key`.
*
* @param {String|IDBKeyRange} key
* @param {Function} cb
*/
Index.prototype.count = function(key, cb) {
var name = this.store.name;
var indexName = this.name;
this.store.db.transaction('readonly', [name], function(err, tr) {
if (err) return cb(err);
var index = tr.objectStore(name).index(indexName);
var req = index.count(parseRange(key));
req.onerror = cb;
req.onsuccess = function onsuccess(e) { cb(null, e.target.result) };
});
};
/**
* Create cursor.
* Proxy to `this.store` for convinience.
*
* @param {Object} opts
* @param {Function} cb
*/
Index.prototype.cursor = function(opts, cb) {
opts.index = this.name;
this.store.cursor(opts, cb);
};
},{"idb-range":6}],2:[function(require,module,exports){
var type = require('component-type');
var parseRange = require('idb-range');
/**
* Expose `Store`.
*/
module.exports = Store;
/**
* Initialize new `Store`.
*
* @param {String} name
* @param {Object} opts
*/
function Store(name, opts) {
this.db = null;
this.name = name;
this.indexes = {};
this.opts = opts;
this.key = opts.key || opts.keyPath || undefined;
this.increment = opts.increment || opts.autoIncretement || undefined;
}
/**
* Get index by `name`.
*
* @param {String} name
* @return {Index}
*/
Store.prototype.index = function(name) {
return this.indexes[name];
};
/**
* Put (create or replace) `key` to `val`.
*
* @param {String|Object} [key] is optional when store.key exists.
* @param {Any} val
* @param {Function} cb
*/
Store.prototype.put = function(key, val, cb) {
var name = this.name;
var keyPath = this.key;
if (keyPath) {
if (type(key) == 'object') {
cb = val;
val = key;
key = null;
} else {
val[keyPath] = key;
}
}
this.db.transaction('readwrite', [name], function(err, tr) {
if (err) return cb(err);
var objectStore = tr.objectStore(name);
var req = keyPath ? objectStore.put(val) : objectStore.put(val, key);
tr.onerror = tr.onabort = req.onerror = cb;
tr.oncomplete = function oncomplete() { cb(null, req.result) };
});
};
/**
* Get `key`.
*
* @param {String} key
* @param {Function} cb
*/
Store.prototype.get = function(key, cb) {
var name = this.name;
this.db.transaction('readonly', [name], function(err, tr) {
if (err) return cb(err);
var objectStore = tr.objectStore(name);
var req = objectStore.get(key);
req.onerror = cb;
req.onsuccess = function onsuccess(e) { cb(null, e.target.result) };
});
};
/**
* Del `key`.
*
* @param {String} key
* @param {Function} cb
*/
Store.prototype.del = function(key, cb) {
var name = this.name;
this.db.transaction('readwrite', [name], function(err, tr) {
if (err) return cb(err);
var objectStore = tr.objectStore(name);
var req = objectStore.delete(key);
tr.onerror = tr.onabort = req.onerror = cb;
tr.oncomplete = function oncomplete() { cb() };
});
};
/**
* Count.
*
* @param {Function} cb
*/
Store.prototype.count = function(cb) {
var name = this.name;
this.db.transaction('readonly', [name], function(err, tr) {
if (err) return cb(err);
var objectStore = tr.objectStore(name);
var req = objectStore.count();
req.onerror = cb;
req.onsuccess = function onsuccess(e) { cb(null, e.target.result) };
});
};
/**
* Clear.
*
* @param {Function} cb
*/
Store.prototype.clear = function(cb) {
var name = this.name;
this.db.transaction('readwrite', [name], function(err, tr) {
if (err) return cb(err);
var objectStore = tr.objectStore(name);
var req = objectStore.clear();
tr.onerror = tr.onabort = req.onerror = cb;
tr.oncomplete = function oncomplete() { cb() };
});
};
/**
* Perform batch operation.
*
* @param {Object} vals
* @param {Function} cb
*/
Store.prototype.batch = function(vals, cb) {
var name = this.name;
var keyPath = this.key;
var keys = Object.keys(vals);
this.db.transaction('readwrite', [name], function(err, tr) {
if (err) return cb(err);
var store = tr.objectStore(name);
var current = 0;
tr.onerror = tr.onabort = cb;
tr.oncomplete = function oncomplete() { cb() };
next();
function next() {
if (current >= keys.length) return;
var currentKey = keys[current];
var currentVal = vals[currentKey];
var req;
if (currentVal === null) {
req = store.delete(currentKey);
} else if (keyPath) {
if (!currentVal[keyPath]) currentVal[keyPath] = currentKey;
req = store.put(currentVal);
} else {
req = store.put(currentVal, currentKey);
}
req.onerror = cb;
req.onsuccess = next;
current += 1;
}
});
};
/**
* Get all.
*
* @param {Function} cb
*/
Store.prototype.all = function(cb) {
var result = [];
this.cursor({ iterator: iterator }, function(err) {
err ? cb(err) : cb(null, result);
});
function iterator(cursor) {
result.push(cursor.value);
cursor.continue();
}
};
/**
* Create read cursor for specific `range`,
* and pass IDBCursor to `iterator` function.
* https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor
*
* @param {Object} opts:
* {IDBRange|Object} range - passes to .openCursor()
* {Function} iterator - function to call with IDBCursor
* {String} [index] - name of index to start cursor by index
* @param {Function} cb - calls on end or error
*/
Store.prototype.cursor = function(opts, cb) {
var name = this.name;
this.db.transaction('readonly', [name], function(err, tr) {
if (err) return cb(err);
var store = opts.index
? tr.objectStore(name).index(opts.index)
: tr.objectStore(name);
var req = store.openCursor(parseRange(opts.range));
req.onerror = cb;
req.onsuccess = function onsuccess(e) {
var cursor = e.target.result;
cursor ? opts.iterator(cursor) : cb();
};
});
};
},{"component-type":5,"idb-range":6}],3:[function(require,module,exports){
var type = require('component-type');
var Store = require('./idb-store');
var Index = require('./idb-index');
/**
* Expose `Schema`.
*/
module.exports = Schema;
/**
* Initialize new `Schema`.
*/
function Schema() {
if (!(this instanceof Schema)) return new Schema();
this._stores = {};
this._current = {};
this._versions = {};
}
/**
* Set new version.
*
* @param {Number} version
* @return {Schema}
*/
Schema.prototype.version = function(version) {
if (type(version) != 'number' || version < 1 || version < this.getVersion())
throw new TypeError('not valid version');
this._current = { version: version, store: null };
this._versions[version] = {
stores: [], // db.createObjectStore
dropStores: [], // db.deleteObjectStore
indexes: [], // store.createIndex
dropIndexes: [], // store.deleteIndex
version: version // version
};
return this;
};
/**
* Add store.
*
* @param {String} name
* @param {Object} [opts] { key: false }
* @return {Schema}
*/
Schema.prototype.addStore = function(name, opts) {
if (type(name) != 'string') throw new TypeError('`name` is required');
if (this._stores[name]) throw new TypeError('store is already defined');
var store = new Store(name, opts || {});
this._stores[name] = store;
this._versions[this.getVersion()].stores.push(store);
this._current.store = store;
return this;
};
/**
* Drop store.
*
* @param {String} name
* @return {Schema}
*/
Schema.prototype.dropStore = function(name) {
if (type(name) != 'string') throw new TypeError('`name` is required');
var store = this._stores[name];
if (!store) throw new TypeError('store is not defined');
delete this._stores[name];
this._versions[this.getVersion()].dropStores.push(store);
return this;
};
/**
* Add index.
*
* @param {String} name
* @param {String|Array} field
* @param {Object} [opts] { unique: false, multi: false }
* @return {Schema}
*/
Schema.prototype.addIndex = function(name, field, opts) {
if (type(name) != 'string') throw new TypeError('`name` is required');
if (type(field) != 'string' && type(field) != 'array') throw new TypeError('`field` is required');
var store = this._current.store;
if (store.indexes[name]) throw new TypeError('index is already defined');
var index = new Index(store, name, field, opts || {});
store.indexes[name] = index;
this._versions[this.getVersion()].indexes.push(index);
return this;
};
/**
* Drop index.
*
* @param {String} name
* @return {Schema}
*/
Schema.prototype.dropIndex = function(name) {
if (type(name) != 'string') throw new TypeError('`name` is required');
var index = this._current.store.indexes[name];
if (!index) throw new TypeError('index is not defined');
delete this._current.store.indexes[name];
this._versions[this.getVersion()].dropIndexes.push(index);
return this;
};
/**
* Change current store.
*
* @param {String} name
* @return {Schema}
*/
Schema.prototype.getStore = function(name) {
if (type(name) != 'string') throw new TypeError('`name` is required');
if (!this._stores[name]) throw new TypeError('store is not defined');
this._current.store = this._stores[name];
return this;
};
/**
* Get version.
*
* @return {Number}
*/
Schema.prototype.getVersion = function() {
return this._current.version;
};
/**
* Generate onupgradeneeded callback.
*
* @return {Function}
*/
Schema.prototype.callback = function() {
var versions = Object.keys(this._versions)
.map(function(v) { return this._versions[v] }, this)
.sort(function(a, b) { return a.version - b.version });
return function onupgradeneeded(e) {
var db = e.target.result;
var tr = e.target.transaction;
versions.forEach(function(versionSchema) {
if (e.oldVersion >= versionSchema.version) return;
versionSchema.stores.forEach(function(s) {
var options = {};
// Only pass the options that are explicitly specified to createObjectStore() otherwise IE/Edge
// can throw an InvalidAccessError - see https://msdn.microsoft.com/en-us/library/hh772493(v=vs.85).aspx
if (typeof s.key !== 'undefined') options.keyPath = s.key;
if (typeof s.increment !== 'undefined') options.autoIncrement = s.increment;
db.createObjectStore(s.name, options);
});
versionSchema.dropStores.forEach(function(s) {
db.deleteObjectStore(s.name);
});
versionSchema.indexes.forEach(function(i) {
var store = tr.objectStore(i.store.name);
store.createIndex(i.name, i.field, {
unique: i.unique,
multiEntry: i.multi
});
});
versionSchema.dropIndexes.forEach(function(i) {
var store = tr.objectStore(i.store.name);
store.deleteIndex(i.name);
});
});
};
};
},{"./idb-index":1,"./idb-store":2,"component-type":5}],4:[function(require,module,exports){
(function (global){
var type = require('component-type');
var Schema = require('./schema');
var Store = require('./idb-store');
var Index = require('./idb-index');
/**
* Expose `Treo`.
*/
exports = module.exports = Treo;
/**
* Initialize new `Treo` instance.
*
* @param {String} name
* @param {Schema} schema
*/
function Treo(name, schema) {
if (!(this instanceof Treo)) return new Treo(name, schema);
if (type(name) != 'string') throw new TypeError('`name` required');
if (!(schema instanceof Schema)) throw new TypeError('not valid schema');
this.name = name;
this.status = 'close';
this.origin = null;
this.stores = schema._stores;
this.version = schema.getVersion();
this.onupgradeneeded = schema.callback();
// assign db property to each store
Object.keys(this.stores).forEach(function(storeName) {
this.stores[storeName].db = this;
}, this);
}
/**
* Expose core classes.
*/
exports.schema = Schema;
exports.cmp = cmp;
exports.Treo = Treo;
exports.Schema = Schema;
exports.Store = Store;
exports.Index = Index;
/**
* Use plugin `fn`.
*
* @param {Function} fn
* @return {Treo}
*/
Treo.prototype.use = function(fn) {
fn(this, exports);
return this;
};
/**
* Drop.
*
* @param {Function} cb
*/
Treo.prototype.drop = function(cb) {
var name = this.name;
this.close(function(err) {
if (err) return cb(err);
var req = indexedDB().deleteDatabase(name);
req.onerror = cb;
req.onsuccess = function onsuccess() { cb() };
});
};
/**
* Close.
*
* @param {Function} cb
*/
Treo.prototype.close = function(cb) {
if (this.status == 'close') return cb();
this.getInstance(function(err, db) {
if (err) return cb(err);
db.origin = null;
db.status = 'close';
db.close();
cb();
});
};
/**
* Get store by `name`.
*
* @param {String} name
* @return {Store}
*/
Treo.prototype.store = function(name) {
return this.stores[name];
};
/**
* Get db instance. It starts opening transaction only once,
* another requests will be scheduled to queue.
*
* @param {Function} cb
*/
Treo.prototype.getInstance = function(cb) {
if (this.status == 'open') return cb(null, this.origin);
if (this.status == 'opening') return this.queue.push(cb);
this.status = 'opening';
this.queue = [cb]; // queue callbacks
var that = this;
var req = indexedDB().open(this.name, this.version);
req.onupgradeneeded = this.onupgradeneeded;
req.onerror = req.onblocked = function onerror(e) {
that.status = 'error';
that.queue.forEach(function(cb) { cb(e) });
delete that.queue;
};
req.onsuccess = function onsuccess(e) {
that.origin = e.target.result;
that.status = 'open';
that.origin.onversionchange = function onversionchange() {
that.close(function() {});
};
that.queue.forEach(function(cb) { cb(null, that.origin) });
delete that.queue;
};
};
/**
* Create new transaction for selected `stores`.
*
* @param {String} type (readwrite|readonly)
* @param {Array} stores - follow indexeddb semantic
* @param {Function} cb
*/
Treo.prototype.transaction = function(type, stores, cb) {
this.getInstance(function(err, db) {
err ? cb(err) : cb(null, db.transaction(stores, type));
});
};
/**
* Compare 2 values using IndexedDB comparision algotihm.
*
* @param {Mixed} value1
* @param {Mixed} value2
* @return {Number} -1|0|1
*/
function cmp() {
return indexedDB().cmp.apply(indexedDB(), arguments);
}
/**
* Dynamic link to `global.indexedDB` for polyfills support.
*
* @return {IDBDatabase}
*/
function indexedDB() {
return global._indexedDB
|| global.indexedDB
|| global.msIndexedDB
|| global.mozIndexedDB
|| global.webkitIndexedDB;
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./idb-index":1,"./idb-store":2,"./schema":3,"component-type":5}],5:[function(require,module,exports){
/**
* toString ref.
*/
var toString = Object.prototype.toString;
/**
* Return the type of `val`.
*
* @param {Mixed} val
* @return {String}
* @api public
*/
module.exports = function(val){
switch (toString.call(val)) {
case '[object Date]': return 'date';
case '[object RegExp]': return 'regexp';
case '[object Arguments]': return 'arguments';
case '[object Array]': return 'array';
case '[object Error]': return 'error';
}
if (val === null) return 'null';
if (val === undefined) return 'undefined';
if (val !== val) return 'nan';
if (val && val.nodeType === 1) return 'element';
val = val.valueOf
? val.valueOf()
: Object.prototype.valueOf.apply(val)
return typeof val;
};
},{}],6:[function(require,module,exports){
(function (global){
/**
* Parse `opts` to valid IDBKeyRange.
* https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange
*
* @param {Object} opts
* @return {IDBKeyRange}
*/
module.exports = function range(opts) {
var IDBKeyRange = global.IDBKeyRange || global.webkitIDBKeyRange
if (opts instanceof IDBKeyRange) return opts
if (typeof opts === 'undefined') return null
if (!isObject(opts)) return IDBKeyRange.only(opts)
var keys = Object.keys(opts).sort()
if (keys.length == 1) {
var key = keys[0]
var val = opts[key]
switch (key) {
case 'eq': return IDBKeyRange.only(val)
case 'gt': return IDBKeyRange.lowerBound(val, true)
case 'lt': return IDBKeyRange.upperBound(val, true)
case 'gte': return IDBKeyRange.lowerBound(val)
case 'lte': return IDBKeyRange.upperBound(val)
default: throw new TypeError('`' + key + '` is not valid key')
}
} else {
var x = opts[keys[0]]
var y = opts[keys[1]]
var pattern = keys.join('-')
switch (pattern) {
case 'gt-lt': return IDBKeyRange.bound(x, y, true, true)
case 'gt-lte': return IDBKeyRange.bound(x, y, true, false)
case 'gte-lt': return IDBKeyRange.bound(x, y, false, true)
case 'gte-lte': return IDBKeyRange.bound(x, y, false, false)
default: throw new TypeError('`' + pattern +'` are conflicted keys')
}
}
}
/**
* Check if `obj` is an object (an even not an array).
*
* @param {Object} obj
* @return {Boolean}
*/
function isObject(obj) {
return Object.prototype.toString.call(obj) == '[object Object]'
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[4])(4)
});