-
Notifications
You must be signed in to change notification settings - Fork 0
/
stubifierServiceWorker.js
45 lines (36 loc) · 1008 Bytes
/
stubifierServiceWorker.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
const channel = new BroadcastChannel('stubify_channel');
var fakeEndpoints = [];
channel.onmessage = function(event) {
fakeEndpoints = event.data;
};
self.addEventListener('install', function(event) {
self.skipWaiting();
});
function matchUrl(u, v) {
const uA = u.split('/');
const vA = v.split('/');
if (uA.length != vA.length) {
return false;
}
for (var i=0; i<uA.length; i++) {
if (uA[i] != vA[i] && uA[i] != '*'){
return false;
}
}
return true;
}
self.addEventListener('fetch', function(event) {
var relativeUrl = event.request.url.replace(/^(?:\/\/|[^\/]+)*\//, "");
const fakeEndpoint =
fakeEndpoints.find(
function(e){
return matchUrl(e.url, relativeUrl);
});
if (fakeEndpoint){
blob = new Blob([JSON.stringify(fakeEndpoint.data)], {type : 'application/json'});
var fakeResponse = new Response(blob);
event.respondWith(Promise.resolve(fakeResponse));
return;
}
event.respondWith(fetch(event.request));
});