-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.js
53 lines (46 loc) · 1.14 KB
/
test.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
import fetch from "node-fetch";
import Websocket from "ws";
// Set up Websocket endpoint
const url = process.env.WS_URL ?? "http://localhost:8080";
// Establish Websocket connection
const ws = new Websocket(
url.replace("https://", "wss://").replace("http://", "ws://")
);
ws.on("open", () => {
// Output incoming message
ws.on("message", (data) => {
console.log(safeJsonParse(data));
});
// Send test messages
ws.send(createMessage({ type: "CHAT", save: true }));
ws.send(createMessage({ type: "USER" }));
// Get history
fetch(`${url}/messages?secret=${process.env.SECRET}`)
.then((res) => res.text())
.then((res) => console.log(res))
.catch((e) => console.log(e));
});
const createMessage = (message) => {
const id = "abcdefghijklmnopqrstuvwxyz"
.split("")
.sort(() => Math.random() - 0.5)
.slice(0, 16)
.join("");
return JSON.stringify({
id,
datetime: new Date().toISOString(),
type: "",
channel: "",
userId: "",
userName: "",
value: "",
...message,
});
};
const safeJsonParse = (str) => {
try {
return JSON.parse(str);
} catch (err) {
return str;
}
};