-
Notifications
You must be signed in to change notification settings - Fork 7
/
web-push-notification.js
79 lines (68 loc) · 2.25 KB
/
web-push-notification.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
module.exports = function (RED) {
function WebPushNotificationNode (n) {
RED.nodes.createNode(this, n)
this.content = n
var node = this
this.on('input', (msg) => {
let payload = {}
node.status({})
try {
if (node.content.title) {
if (!payload.notification) {
payload.notification = {}
}
payload.notification.title = node.content.title
}
if (node.content.body) {
if (!payload.notification) {
payload.notification = {}
}
payload.notification.body = node.content.body
}
if (node.content.sound) {
if (!payload.notification) {
payload.notification = {}
}
payload.notification.sound = node.content.sound
}
if (node.content.payload) {
let data = {}
let keyValArray = JSON.parse(node.content.payload)
for (let i = 0; i < keyValArray.length; i++) {
switch (keyValArray[i].type) {
case 'str':
var value = String(keyValArray[i].value)
data[keyValArray[i].key] = value
break
case 'num':
var value = parseFloat(keyValArray[i].value)
if (!Number.isNaN(value)) {
data[keyValArray[i].key] = value
} else {
throw new Error('Could not parse ' + keyValArray[i].value + ' into a number.')
}
break
case 'bool':
var value = keyValArray[i].value == true
data[keyValArray[i].key] = value
break
case 'json':
var value = JSON.parse(keyValArray[i].value)
data[keyValArray[i].key] = value
break
}
}
payload.data = data
}
msg.notification = payload
node.send(msg)
} catch (err) {
node.status({ fill: 'red', shape: 'dot', text: err.message })
}
})
this.on('close', () => {
node.status({})
})
}
RED.nodes.registerType('web-push-notification', WebPushNotificationNode)
}