-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlanyard.js
74 lines (59 loc) · 2.33 KB
/
lanyard.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
const CONSTANTS = {
API_URL: "https://api.lanyard.rest/v1",
WEBSOCKET_URL: "wss://api.lanyard.rest/socket",
ORIGIN: "wss://api.lanyard.rest",
HEARTBEAT_PERIOD: 1000 * 30
}
async function lanyard(opts) {
if (!opts) throw new Error("Specify an options object");
if (!opts.userId) throw new Error("Specify a user ID");
if (opts.socket) {
if (!opts.onPresenceUpdate) throw new Error("Specify onPresenceUpdate callback");
const supportsWebSocket = "WebSocket" in window || "MozWebSocket" in window;
if (!supportsWebSocket) throw new Error("Browser doesn't support WebSocket connections.",);
const socket = new WebSocket(CONSTANTS.WEBSOCKET_URL);
const subscription = typeof opts.userId == "string" ? "subscribe_to_id" : "subscribe_to_ids"
socket.addEventListener("open", () => {
socket.send(
JSON.stringify({
op: 2,
d: {
[subscription]: opts.userId,
},
}),
);
setInterval(() => {
socket.send(
JSON.stringify({
op: 3,
}),
);
}, CONSTANTS.HEARTBEAT_PERIOD);
});
socket.addEventListener("message", ({ data, origin }) => {
if (origin == CONSTANTS.ORIGIN) {
const { t, d } = JSON.parse(data)
if (t === "INIT_STATE" || t === "PRESENCE_UPDATE") {
opts.onPresenceUpdate(d)
}
}
});
return socket;
} else {
if (typeof opts.userId == "string") {
const res = await fetch(`${CONSTANTS.API_URL}/users/${opts.userId}`);
const body = await res.json();
if (!body.success) throw new Error(body.error?.message || "An invalid error occured");
return body.data;
} else {
const val = [];
for (const userId of opts.userId) {
const res = await fetch(`${CONSTANTS.API_URL}/users/${userId}`);
const body = await res.json();
if (!body.success) throw new Error(body.error?.message || "An invalid error occured");
val.push(body.data)
}
return val;
}
}
}