forked from JheSue/atomic-gravity
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgravity-publish.js
More file actions
112 lines (92 loc) · 2.11 KB
/
gravity-publish.js
File metadata and controls
112 lines (92 loc) · 2.11 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
module.exports = function(RED) {
function PublishNode(config) {
RED.nodes.createNode(this, config);
var node = this;
this.server = RED.nodes.getNode(config.server)
function setStatus(type) {
switch(type) {
case 'connected':
node.status({
fill: 'green',
shape: 'dot',
text: 'connected'
});
break;
case 'connecting':
node.status({
fill: 'yellow',
shape: 'ring',
text: 'connecting'
});
break;
case 'disconnected':
node.status({
fill: 'red',
shape: 'ring',
text: 'disconnected'
});
break;
}
}
setStatus('disconnected');
// Initializing gravity client
let uuid = require('uuid');
let Gravity = require('gravity-sdk');
(async () => {
if (!node.server) {
setStatus('disconnected');
return;
}
let accessToken = '';
if (node.credentials) {
accessToken = node.credentials.accessToken || '';
}
let client = new Gravity.Client({
servers: node.server.server + ':' + node.server.port,
domain: config.domain || 'default',
token: accessToken,
});
node.gravityClient = client;
try {
setStatus('connecting');
// Connect to gravity
await client.connect();
client.on('disconnect', () => {
setStatus('disconnected');
});
client.on('reconnect', () => {
setStatus('connecting');
});
} catch(e) {
node.error(e);
return;
}
setStatus('connected');
})();
node.on('input', async (msg, send, done) => {
if (!msg.eventName) {
return done();
}
// set msgID
let opts = {}
if (msg.natsMsgId) {
opts.msgID = msg.natsMsgId;
}
try {
await node.gravityClient.publish(msg.eventName, JSON.stringify(msg.payload), opts);
done();
} catch(e) {
node.error(e);
}
});
node.on('close', () => {
node.gravityClient.disconnect();
});
}
RED.nodes.registerType('Gravity Publish', PublishNode, {
credentials: {
appID: { type: 'text' },
accessToken: { type: 'text' }
}
});
}