-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.js
More file actions
73 lines (68 loc) · 1.75 KB
/
utils.js
File metadata and controls
73 lines (68 loc) · 1.75 KB
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
const jwt = require("jsonwebtoken");
const admin = require("./config/notice.config");
function parseJWTPayload(token) {
return jwt.verify(token, process.env.JWT_SECRET_KEY, function (err, decoded) {
if (err) throw err;
return decoded;
});
}
async function sendNotice(device_tokens, notice) {
if (device_tokens.length == 0) {
return false;
} else if (device_tokens.length == 1) {
let message = {
data: {
title: notice.title,
body: notice.body,
link: notice.link,
type: notice.type,
},
token: device_tokens[0].device_token,
};
admin
.messaging()
.send(message)
.then((response) => {
// Response is a message ID string.
console.log("Successfully sent message:", response);
})
.catch((error) => {
console.log("Error sending message:", error);
return false;
});
return true;
} else {
const token_list = [];
for (let i = 0; i < device_tokens.length; i++)
token_list.push(device_tokens[i].device_token);
let message = {
data: {
title: notice.title,
body: notice.body,
link: notice.link,
type: notice.type,
},
tokens: token_list,
};
admin
.messaging()
.sendMulticast(message)
.then((response) => {
if (response.failureCount > 0) {
const failedTokens = [];
response.responses.forEach((resp, idx) => {
if (!resp.success) {
failedTokens.push(device_tokens[idx]);
}
});
console.log("List of tokens that caused failures: " + failedTokens);
return false;
}
});
return true;
}
}
module.exports = {
parseJWTPayload,
sendNotice,
};