AngularJS + TypeScript : Write a Service Worker in Typescript

Viewed 1733

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);
      })
    )
  };
});
1 Answers

TypeScript is a super set of JavaScript. This implies that all valid JavaScript code is also valid Type Script code. Following are my steps in converting JS code to TS

  1. Find appropriate typings

    You can find Typings for service worker API here

  2. Add proper typings to all variables to avoid wrong typing collision.

  3. Adding encapsulations to functions and exporting it as class.

  4. Use build tools (Webpack) that converts TypeScript to JavaScript if necessary

For example, suppose we have a module let say Greeter it has an instance variable greeting and a method greet which appends hello to greeting.and the code for the module is shown below

var Greeter = /** @class */ (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
}());
alert(new Greeter("samuel").greet());

The corresponding representation of the above js function in typescript is as below

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

alert(new Greeter("samuel").greet());

The official documentation for migration can be found here

Related