-
Notifications
You must be signed in to change notification settings - Fork 0
/
service-worker.js
59 lines (53 loc) · 2.04 KB
/
service-worker.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
const NOTIFICATION_ICON = "/public/pictures/xmessenger-logo.jpg";
/**
* Runtime swState object. Entries are provided from main thread.
* {
* user: {} - Current user info.
* }
* @type {Object}
*/
let swState = {user: null}, itemsToNotifyAbout = new Map();
const parsePushData = event => {
try {
return Promise.resolve(event.data.json());
} catch (e) {
console.error(e);
return Promise.reject(`Push data: ${event.data.text()}`);
}
};
const showNotification = ({title, options}) => {
if (Notification.permission !== "granted") return;
return self.registration.showNotification(title, {
icon: NOTIFICATION_ICON, ...options
});
};
const notifyOnIncomingRequest = eventDetails => {
const {eventName, detail} = eventDetails, {request} = detail, {user} = swState;
if (!!user && !itemsToNotifyAbout.has(request["id"])) { // avoid duplicate notifications;
if (eventName === "onSendRequest" && request["recipient"]["id"] === user["id"]) {
itemsToNotifyAbout.set(request["id"], request);
showNotification({
title: "New friendship request!",
options: {body: request["sender"]["name"] + " wants to befriend with you."}
});
} else if (eventName === "onProcessRequest" && request["sender"]["id"] === user["id"] && request["approved"]) {
itemsToNotifyAbout.set(request["id"], request);
showNotification({
title: "Friendship request approved!",
options: {body: request["recipient"]["name"] + " accepted your friendship request."}
});
}
if (itemsToNotifyAbout.size >= 15) {
itemsToNotifyAbout.clear();
}
}
};
self.addEventListener("push", event => {
parsePushData(event)
.then(eventData => notifyOnIncomingRequest(eventData))
.catch(error => console.warn(error));
});
self.addEventListener("message", event => {
const newSwState = JSON.parse(event.data);
swState = Object.assign(swState, newSwState);
});