forked from udacity/mws-restaurant-stage-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw.js
246 lines (188 loc) · 5.59 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
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
var name = 'restaurants-simple-cache-v2',
filesToCache = [
'./',
'./index.html',
'./restaurant.html',
'./sw.min.js',
'./dest/styles.css',
'./dest/main.js',
'./dest/restaurant_info.js'
];
self.addEventListener('install', function(event) {
event.waitUntil(openDatabase().then(function() {
}).catch(function(e) {
console.log(e);
})
);
event.waitUntil(
caches.open(name).then(function(cache) {
return cache.addAll(filesToCache);
}).catch(function(e) {
console.log(e);
})
);
});
self.addEventListener('activate', function (event) {
self.clients.matchAll({
includeUncontrolled: true
}).then(function(clientList) {
var urls = clientList.map(function(client) {
return client.url;
});
console.log('[ServiceWorker] Matching clients:', urls.join(', '));
});
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(cacheNames.filter(function(cacheName) {
return cacheName.startsWith('restaurants-');
}).map(function(cacheName) {
return caches.delete(cacheName);
})
);
}).then(function() {
return self.clients.claim();
}).catch(function(e) {
console.log(e);
})
);
});
self.addEventListener('fetch', function(event) {
if (event.request.method != 'GET' ||
(event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin')) {
return;
}
var requestUrl = new URL(event.request.url);
if (requestUrl.origin === location.origin) {
if (requestUrl.pathname.startsWith('/img')) {
event.respondWith(servePhoto(event.request));
return;
}
}
// all json
if (requestUrl.origin.indexOf('localhost:1337') != -1) {
var errRspnd;
var url = requestUrl.href;
event.respondWith(fetch(event.request).then(function(response) {
putDBCachedMessage(url, response.clone());
return response;
}).catch(function(e) {
return getDBCachedMessage(url).then(function(resp) {
return resp;
}).catch(function(e) {
return e;
});
})
);
return;
}
// non-json
event.respondWith(
caches.open(name).then(function(cache) {
return cache.match(event.request).then(function (response) {
return response || fetch(event.request).then(function(response) {
cache.put(event.request, response.clone());
return response;
}).catch(function(e) {
console.log(e);
});
});
}).catch(function(e) {
console.log(e);
})
);
});
function servePhoto(request) {
var storageUrl = request.url.replace(/-\d+px\.jpg$/, '');
return caches.open(name).then(function(cache) {
return cache.match(storageUrl).then(function(response) {
if (response) return response;
return fetch(request).then(function(networkResponse) {
cache.put(storageUrl, networkResponse.clone());
return networkResponse;
}).catch(function(e) {
console.log(e);
});
}).catch(function(e) {
console.log(e);
});
});
}
/* temporary store */
const syncStore = {}
self.addEventListener('message', event => {
if(event.data.type === 'review' || event.data.type === 'favorite') {
const id = event.data.uuid;
syncStore[id] = event;
// register a sync and pass the id as tag for it to get the data
self.registration.sync.register(id)
}
});
self.addEventListener('sync', event => {
// get the data by tag
const savedEvent = syncStore[event.tag];
// do not delete for testing purposes
// delete syncStore[event.tag]
console.log('=== Syncing ===');
console.log('=== url: ' + savedEvent.data.url);
console.log('=== options: ' + JSON.stringify(savedEvent.data.options));
event.waitUntil(fetch(savedEvent.data.url, savedEvent.data.options).then(function(response) {
return response.json();
}).then(function(data) {
data.type = savedEvent.data.type;
savedEvent.ports[0].postMessage(data);
}).catch(function(err) {
console.error(err);
})
);
});
// ===================================== indexedDB ================================
var dbName = 'restaurants-simple-idb'
var objStoreName = 'mws-restaurant-calls'
var idbDatabase;
function openDatabase() {
var indexedDBOpenRequest = indexedDB.open(dbName, 1);
return new Promise((resolve, reject) => {
indexedDBOpenRequest.onupgradeneeded = function() {
this.result.createObjectStore(objStoreName, {keyPath: 'url'});
};
indexedDBOpenRequest.onsuccess = function() {
idbDatabase = this.result;
resolve();
};
indexedDBOpenRequest.onerror = function(error) {
console.error('IndexedDB error:', error);
reject();
};
});
};
function getObjectStore() {
return idbDatabase.transaction(objStoreName, 'readwrite').objectStore(objStoreName);
};
function getDBCachedMessage(reqKey) {
var getRequest = getObjectStore().get(reqKey);
return new Promise((resolve, reject) => {
getRequest.onsuccess = function(e) {
var item = e.target.result;
if (item != null) {
resolve( new Response(JSON.stringify(item.data), {
headers: {
'content-type': 'application/json'
}
}));
} else {
resolve(null);
}
};
getRequest.onerror = function(e) {
reject(null);
};
});
};
function putDBCachedMessage(reqKey, response) {
response.json().then(function(json) {
getObjectStore().put({
url: reqKey,
data: json
});
});
};