-
Notifications
You must be signed in to change notification settings - Fork 2
/
WebPushNotifications.js
64 lines (58 loc) · 1.54 KB
/
WebPushNotifications.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
const webpush = require('web-push');
const { firestore } = require('firebase-admin');
/**
* @returns {void}
*/
function init(publicKey, privateKey) {
webpush.setVapidDetails(
'mailto:arquidiocesis.itesm.mty@gmail.com',
publicKey ?? process.env.VAPID_PUBLIC_KEY,
privateKey ?? process.env.VAPID_PRIVATE_KEY
);
}
/**
*
* @param {string} id
* @param {{endpoint: string, expirationTime: number, keys: {auth: string, p256dh: string}}} subscription
* @returns {Promise<void>}
*/
async function saveSubscriptionForUserByID(id, subscription) {
await firestore()
.collection('users')
.doc(id)
.update({
web_push_notifications_info: firestore.FieldValue.arrayUnion(
subscription
),
});
}
/**
* @param {string} id
* @param {{title: string, body: string, data: Object}} payload
* @returns {Promise<void>}
*/
async function sendToUserByID(id, payload) {
const user = await firestore().collection('users').doc(id).get();
if (!user.exists) {
throw new Error(
`Attempted to send notification to non-existent user with ID: ${id}`
);
}
const { web_push_notifications_info } = user.data();
if (web_push_notifications_info != null) {
await Promise.all(
web_push_notifications_info.map((subscription) =>
webpush.sendNotification(subscription, JSON.stringify(payload))
)
);
} else {
throw new Error(
`Attempted to send notification to unsubscribed user with ID: ${id}`
);
}
}
module.exports = {
init,
saveSubscriptionForUserByID,
sendToUserByID,
};