-
Notifications
You must be signed in to change notification settings - Fork 3
/
indexDBService.js
74 lines (54 loc) · 1.79 KB
/
indexDBService.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
function getDBRequestObject() {
var request = indexedDB.open("message_offline_database");
request.onerror = (event) => {
console.error("IndexedDB open failed :", event.target.errorCode);
};
request.onupgradeneeded = (event) => {
this.createDatabaseStructure(event);
};
return request;
}
function getStoreObject(db) {
var tx = db.transaction('message_offline', 'readwrite');
return tx.objectStore('message_offline');
}
function createDatabaseStructure(event) {
var db = event.target.result;
var objStore = db.createObjectStore("message_offline", {keyPath : 'id', autoIncrement : true});
objStore.createIndex('author', 'author', {unique : false});
objStore.createIndex('content', 'content', {unique : false});
}
function clearOfflineMessages() {
var request = this.getDBRequestObject();
request.onsuccess = (event) => {
var store = this.getStoreObject(event.target.result);
store.clear();
}
}
function saveMessageOffline(author, content) {
var request = this.getDBRequestObject();
request.onsuccess = (event) => {
var store = this.getStoreObject(event.target.result);
var rq = store.add({author : author, content : content});
rq.onerror = (error) => {
console.log('IndexedDB insert error : ' + error);
};
rq.onsuccess = (event) => {
console.log('IndexedDB insert success');
};
};
}
function getAllOfflineMessages(success_callback) {
var request = this.getDBRequestObject();
request.onsuccess = (event) => {
var store = this.getStoreObject(event.target.result);
var rq = store.getAll();
rq.onerror = (error) => {
console.log('IndexedDB get all error : ' + error);
};
rq.onsuccess = (event) => {
console.log('IndexedDB get all success');
success_callback(event.target.result);
};
}
}