-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
109 lines (99 loc) · 2.65 KB
/
index.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
98
99
100
101
102
103
104
105
106
107
108
109
const mqtt = require('mqtt');
const { apiFetch } = require('./fetch');
function createClient({ apiUrl = '', API_URL = '', appName = '', wsUrl = '' }) {
let mqttClient;
if (!apiUrl && !API_URL && !appName) {
throw new Error('must have an apiURL, API_URL, or appName');
}
apiUrl = apiUrl || API_URL;
if (!apiUrl) {
apiUrl = `https://a.diyapis.com/${appName}`;
}
if (!appName) {
appName = apiUrl.split('/')[apiUrl.split('/').length - 1];
}
if (!wsUrl) {
const url = new URL(apiUrl);
wsUrl = `${url.protocol === 'https:' ? 'wss:' : 'ws:'}//${url.host}/${appName}`;
}
function getFullTopic(topic) {
if (!topic) {
return;
}
if (topic.startsWith('/')) {
topic = topic.substring(1);
}
return `/${appName}/${topic}`;
}
const client = {
apiUrl,
wsUrl,
apiFetch: (path, options) => {
return apiFetch(apiUrl, path, options);
},
connect: (url, options = {}) => {
url = url || wsUrl;
options = { username: appName, ...options };
mqttClient = mqtt.connect(wsUrl, options);
client.mqttClient = mqttClient;
mqttClient.on('message', (topic, msg) => {
try {
msg = JSON.parse(msg.toString());
mqttClient.emit('json', topic, msg);
} catch (err) {
// continue regardless of error
}
});
return mqttClient;
},
on: (...args) => {
if (mqttClient) {
return mqttClient.on(...args);
}
},
publish: (topic, payload, ...restArgs) => {
topic = getFullTopic(topic);
if (!topic || !mqttClient) {
return;
}
if (typeof payload === 'object') {
payload = JSON.stringify(payload);
} else {
payload = String(payload);
}
return mqttClient.publish(topic, payload, ...restArgs);
},
subscribe: (topic, ...args) => {
topic = getFullTopic(topic);
if (!topic || !mqttClient) {
return;
}
return mqttClient.subscribe(topic, ...args);
},
unsubscribe: (topic, ...args) => {
topic = getFullTopic(topic);
if (!topic || !mqttClient) {
return;
}
return mqttClient.subscribe(topic, ...args);
},
close: (...args) => {
if (mqttClient) {
return mqttClient.close(...args);
}
},
oauthStart: (mode) => {
return client.apiFetch(`/users/oauth_start${mode ? '?mode=' + mode : ''}`);
},
tokenLogin: (token) => {
return client.apiFetch('/users/oauth_token', { method: 'POST', body: { token } });
},
verifyUser: () => {
return client.apiFetch('/users/me');
}
};
return client;
}
module.exports = {
createClient
};