-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw.js
87 lines (63 loc) · 2.5 KB
/
sw.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
self.addEventListener('install', async event => {
console.log('install event')
});
self.addEventListener('fetch', async event => {
console.log('fetch event')
});
self.addEventListener('message', event => {
// event is an ExtendableMessageEvent object
console.log(`The client sent me a message: ${event.data}`);
event.source.postMessage(`Hi client, you sent me ${event.data}`);
});
var request = self.indexedDB.open('EXAMPLE_DB', 1);
request.onsuccess = function(event) {
// some sample products data
var products = [
{id: 1, name: 'Red Men T-Shirt', price: '$3.99'},
{id: 2, name: 'Pink Women Shorts', price: '$5.99'},
{id: 3, name: 'Nike white Shoes', price: '$300'}
];
// get database from event
var db = event.target.result;
// create transaction from database
var transaction = db.transaction('products', 'readwrite');
// add success event handleer for transaction
// you should also add onerror, onabort event handlers
transaction.onsuccess = function(event) {
console.log('[Transaction] ALL DONE!');
};
// get store from transaction
var productsStore = transaction.objectStore('products');
/*************************************/
// put products data in productsStore
products.forEach(function(product){
var db_op_req = productsStore.add(product);
db_op_req.onsuccess = function(event) {
console.log(event.target.result == product.id); // true
}
});
// count number of objects in store
productsStore.count().onsuccess = function(event) {
console.log('[Transaction - COUNT] number of products in store', event.target.result);
};
// get product with id 1
productsStore.get(1).onsuccess = function(event) {
console.log('[Transaction - GET] product with id 1', event.target.result);
};
// update product with id 1
products[0].name = 'Blue Men T-shirt';
productsStore.put(products[0]).onsuccess = function(event) {
console.log('[Transaction - PUT] product with id 1', event.target.result);
};
// delete product with id 2
productsStore.delete(2).onsuccess = function(event) {
console.log('[Transaction - DELETE] deleted with id 2');
};
};
request.onerror = function(event) {
console.log('[onerror]', request.error);
};
request.onupgradeneeded = function(event) {
var db = event.target.result;
var productsStore = db.createObjectStore('products', {keyPath: 'id'});
};