summaryrefslogtreecommitdiff
path: root/src/client/app/sw.js
blob: ac7ea20acfc60ebdcfc60fdb3e72940634f5c777 (plain)
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
/**
 * Service Worker
 */

import composeNotification from './common/scripts/compose-notification';

// キャッシュするリソース
const cachee = [
	'/'
];

// インストールされたとき
self.addEventListener('install', ev => {
	console.info('installed');

	ev.waitUntil(Promise.all([
		self.skipWaiting(), // Force activate
		caches.open(_VERSION_).then(cache => cache.addAll(cachee)) // Cache
	]));
});

// アクティベートされたとき
self.addEventListener('activate', ev => {
	// Clean up old caches
	ev.waitUntil(
		caches.keys().then(keys => Promise.all(
			keys
				.filter(key => key != _VERSION_)
				.map(key => caches.delete(key))
		))
	);
});

// リクエストが発生したとき
self.addEventListener('fetch', ev => {
	ev.respondWith(
		// キャッシュがあるか確認してあればそれを返す
		caches.match(ev.request).then(response =>
			response || fetch(ev.request)
		)
	);
});

// プッシュ通知を受け取ったとき
self.addEventListener('push', ev => {
	// クライアント取得
	ev.waitUntil(self.clients.matchAll({
		includeUncontrolled: true
	}).then(clients => {
		// クライアントがあったらストリームに接続しているということなので通知しない
		if (clients.length != 0) return;

		const { type, body } = ev.data.json();

		const n = composeNotification(type, body);
		return self.registration.showNotification(n.title, {
			body: n.body,
			icon: n.icon,
		});
	}));
});

self.addEventListener('message', ev => {
	if (ev.data == 'clear') {
		caches.keys().then(keys => keys.forEach(key => caches.delete(key)));
	}
});