-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple-idb.js
69 lines (64 loc) · 1.84 KB
/
simple-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
/*
* Simple module to store data in IndexedDB. Not a big enhanced library but simple enough
* abstract the functionalities.
*/
angular.module('simpleIDB', []).provider('$simpleIDB', function() {
var idbSupported = ("indexedDB" in window), name, version, upgrades, _self = this;
this.config = function(obj) {
this.name = obj.name;
this.version = obj.version;
this.upgrades = obj.upgrades;
return this;
};
// Provider methods go inside.
this.$get = ['$q', function($q) {
var dbConnectionStatus = $q.defer(),
dbConnectionPromise = dbConnectionStatus.promise,
connection = idbSupported ? window.indexedDB.open(_self.name, _self.version) : null,
database,
getTransaction = function() {
return database.transaction([_self.name], "readwrite");
},
getStore = function() {
return getTransaction().objectStore(_self.name);
};
// Initiate connection based on configs.
connection ? (function (){
connection.onerror = function() {
dbConnectionStatus.reject();
};
connection.onsuccess = function() {
database = event.target.result;
dbConnectionStatus.resolve();
};
// Create database as needed
connection.onupgradeneeded = function(event) {
database = event.target.result;
currVersion = event.oldVersion;
angular.forEach(_self.upgrades, function(callback, ver) {
if(currVersion < ver) {
callback(database);
}
});
}
})() : dbConnectionStatus.reject();
return {
get : function(key, callback) {
dbConnectionPromise.then(function() {
var request = getStore().get(key);
request.onsuccess = function(event) {
callback(request.result);
};
request.onerror = function() {
callback(null);
};
});
},
put : function(data) {
dbConnectionPromise.then(function() {
getStore().put(data);
});
}
};
}];
});