This repository has been archived by the owner on Jan 3, 2024. It is now read-only.
/
messages.js
97 lines (86 loc) · 2.38 KB
/
messages.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/***
* Copyright (c) 2016 - 2018 Alex Grant (@localnerve), LocalNerve LLC
* Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms.
*
* Message handling for the service worker.
*/
/* global Promise, self, clients */
import debugLib from 'sw/utils/debug';
import { synchronize as pushSync } from './sync/push';
import { initCommand } from './init';
const debug = debugLib('messages');
/***
* Add any new messaging command handlers to this object.
*
* Format of all commands:
* @param {Object} payload - The message payload.
* @param {Function} responder - The sendResponse function with event prebound.
* @returns {Promise} Resolves when complete.
*/
const commands = {
/***
* Handle init messages
*/
init: initCommand,
/**
* Handle pushSync messages
*/
pushSync: (payload, responder) => {
return pushSync(payload.subscriptionId)
.then(() => {
return responder({
error: null
});
})
.catch((error) => {
debug('pushSync failed', error);
return responder({
error: error.toString()
});
});
}
};
/**
* Handle unknown commands
*
* @param {Object} payload - Ignored.
* @param {Function} responder - Function to call to resolve the message
*/
function unknownCommand (payload, responder) {
return responder({
error: 'Unknown command received by service worker.'
});
}
/**
* Sends a response back to the message originator.
* If no source or port, sends to all clients.
*
* @param {Object} event - The message event.
* @param {Object} response - The message response payload.
*/
function sendResponse (event, response) {
let result;
const respondTo = event.data.port || event.source;
if (respondTo) {
respondTo.postMessage(response);
} else {
if (self.clients) {
result = clients.matchAll().then((clients) => {
for (let i = 0; i < clients.length; i++) {
clients[i].postMessage(response);
}
});
}
}
return result || Promise.resolve();
}
self.addEventListener('message', (event) => {
const commandName = event.data.command,
payload = event.data.payload,
command = commands[commandName] || unknownCommand;
debug(`"${commandName}" command received`, payload);
const result = command(payload, sendResponse.bind(null, event));
if ('waitUntil' in event) {
event.waitUntil(result);
}
});