I'm using AngularJS 1.6 and Typescript for my app and i was wondering if there is a way to write a Service Worker in TypeScript?
When i googled i mostly found a lot of tips to write it in Angular2 but i have no experience in Angular2 whatsoever.
I already wrote service workers before but it was in pure js, should i create a service or something considering the fact that i'm using typescript? I know that the pure java script will work but i don't think it's a good way to do this since i mostly use typescript for the rest of the app.
I want to rewrite something like this in classes etc :
var cacheWhiteList = [];
cacheWhiteList.push(cacheName);
cacheWhiteList.push(dataCacheName);
self.addEventListener('install', function(e) {
console.log('[ServiceWorker] Install');
e.waitUntil(
caches.open(cacheName).then(function(cache) {
console.log('[ServiceWorker] Caching app shell');
return cache.addAll(filesToCache.map(url => new Request(url, {
credentials: 'same-origin'
})));
})
);
});
self.addEventListener('activate', function(e) {
console.log('[ServiceWorker] Activate');
e.waitUntil(
caches.keys().then(function(keyList) {
return Promise.all(keyList.map(function(key) {
console.log('[ServiceWorker] Removing old cache', key);
if (cacheWhiteList.indexOf(key) === -1) {
return caches.delete(key);
}
}));
})
);
});
self.addEventListener('push', function(event) {
console.log('Push message received', event);
var notificationBody = "";
event.waitUntil(
fetch('/api/Deploy/LastReleases', {
method: 'get',
credentials: 'same-origin'
}).then(function(response) {
return response.text();
}).then(function(text) {
notificationBody = text;
console.log("body1:" + notificationBody);
var title = 'UDD DELIVERY';
self.registration.showNotification(title, {
body: notificationBody,
icon: '/Content/images/icons/icon-120x120.png',
vibrate: [300, 100, 300],
tag: 'Release-tag',
requireInteraction: true
})
})
);
});
self.addEventListener('notificationclick', function(event) {
event.notification.close();
event.waitUntil(clients.matchAll({
includeUncontrolled: true,
type: 'window'
}).then(activeClients => {
if (activeClients.length > 0) {
activeClients[0].navigate('/');
activeClients[0].focus();
} else {
clients.openWindow('/');
}
}));
});
self.addEventListener('fetch', function(e) {
var dataUrl = '/api/';
var dataUrl2 = '/api/Deploy/LastReleases';
var dataUrl3 = '/api/deploy/Register';
if (e.request.url.indexOf(dataUrl) > 0) {
if (e.request.url.indexOf(dataUrl2) > 0 || e.request.url.indexOf(dataUrl3) > 0) {
e.respondWith(
fetch(e.request)
.then(function(response) {
return response;
})
);
} else {
e.respondWith(
fetch(e.request)
.then(function(response) {
return caches.open(dataCacheName).then(function(cache) {
cache.put(e.request.url, response.clone());
return response;
});
})
);
}
} else {
e.respondWith(
caches.match(e.request).then(function(response) {
return response || fetch(e.request);
})
)
};
});