-
Notifications
You must be signed in to change notification settings - Fork 0
/
ofio.idb.js
99 lines (73 loc) · 2.75 KB
/
ofio.idb.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
define(['ofio/ofio', 'ofio/ofio.events'], function (Ofio) {
var module = new Ofio.Module({
name: 'ofio.idb',
namespace: 'idb',
dependencies: arguments
});
module.init = function () {
this.db = null;
this.db_config = this.parent.db;
this.init_indexed_db();
this.remove_db(this.init_db.bind(this));
};
module.init_indexed_db = function () {
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB.")
}
};
module.init_db = function () {
var db = this.db_config;
var request = indexedDB.open(db.name, db.version);
request.onerror = function (event) {
console.error(event);
};
request.onsuccess = this.ready.bind(this);
request.onupgradeneeded = this.upgrade_db.bind(this);
};
module.ready = function (event) {
console.log('ready');
this.db = event.target.result;
this.parent.emit('idb_ready');
};
module.upgrade_db = function (event) {
console.log('upgrade', event.oldVersion);
this.db = event.target.result;
var versions = this.db_config.versions[this.db_config.name];
for (var i = event.oldVersion + 1; i <= event.newVersion; i++)
versions[i] && versions[i](this);
};
module.create_store = function (name, options) {
console.log('creating', name);
this.db.createObjectStore.apply(this.db, arguments);
};
module.remove_db = function (callback) {
console.log('removing');
var request = indexedDB.deleteDatabase(this.db_config.name);
request.onsuccess = callback;
return request;
};
module.add = function (table, record, callback) {
var store = this.db.transaction(table, 'readwrite').objectStore(table);
var request = store.add(record);
request.onsuccess = callback;
return request;
};
module.get_all = function (table, callback) {
var records = [];
var store = this.db.transaction(table).objectStore(table);
store.openCursor().onsuccess = function (event) {
var cursor = event.target.result;
if (cursor) {
records.push(cursor.value);
cursor.continue();
}
else {
callback(records);
}
};
};
return module;
});