This repository was archived by the owner on Apr 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
76 lines (66 loc) · 1.7 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
"use strict";
const assert = require("assert");
const http = require("http");
const { URL } = require("url");
// test: env-cmd -f ../../dev.env node index.js
assert(process.env.CENTRIFUGO_API_URL, "Empty ENV: CENTRIFUGO_API_URL");
assert(process.env.CENTRIFUGO_API_KEY, "Empty ENV: CENTRIFUGO_API_KEY");
assert(process.env.CENTRIFUGO_SECRET, "Empty ENV: CENTRIFUGO_SECRET");
const url = new URL(process.env.CENTRIFUGO_API_URL);
/**
* Send Data
* @param {String} channel
* @param {{}} data
* @return {Promise<void>}
*/
async function centSend(channel, data = {}) {
assert(channel, "Empty channel name");
const payload = JSON.stringify({
method: "publish",
params: {
channel,
data
}
});
const options = {
hostname: url.hostname,
port: url.port,
path: url.pathname,
method: "POST",
headers: {
Authorization: "apikey " + process.env.CENTRIFUGO_API_KEY,
"Content-Length": Buffer.byteLength(payload)
}
};
return new Promise((resolve, reject) => {
let result = "";
const req = http.request(options, res => {
if (res.statusCode !== 200) {
reject(`Error Send Cent message [${res.statusCode}]`);
}
res.on("data", chunk => {
result += chunk.toString();
});
res.on("end", () => {
resolve();
});
});
req.on("error", e => reject(`Error Send Cent message [${e.message}]`));
req.write(payload);
req.end();
});
}
/**
* Send Data to user
* @param {number} userId
* @param {{}} data
* @return {Promise<void>}
*/
async function centSendUser(userId, data = {}) {
assert(userId, "Empty userId");
return centSend("U#" + userId, data);
}
module.exports = {
centSend,
centSendUser
};