-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.js
97 lines (85 loc) · 2.49 KB
/
api.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
const API_URL = import.meta.env.VITE_API_URL
const USE_HTTPS = JSON.parse(import.meta.env.VITE_USE_HTTPS)
import { receive } from '$lib/utils/receiver.js'
import { overlay, code } from '../../routes/game/_store.js'
let codeValue = ''
code.subscribe(value => {
codeValue = value;
});
export let socket;
export async function send(route = '', body = {}, http = false) {
try {
/*
if (http === true) {
const response = await fetch(`http${USE_HTTPS ? 's' : ''}://${API_URL}${route}`, {
method: 'POST',
body: JSON.stringify(body),
})
if (response.ok && response) {
if (response.status === 204) {
return {}
} else {
return response.json()
}
} else {
throw new Error(response.statusText)
}
} else {
*/
if (!socket || socket.readyState === 3) socket = await connect()
socket.send(JSON.stringify({ route, body: { ...body, ...(codeValue !== '' ? { code: codeValue } : {}) } }))
} catch (error) {
console.error(error)
}
}
function connect(tries = 0) {
return new Promise(function (resolve, reject) {
console.log('Connecting...')
const server = new WebSocket(`ws${USE_HTTPS ? 's' : ''}://${API_URL}/ws`);
const timer = setTimeout(() => {
reject(new Error("WebSocket timeout"));
console.log('Socket connection timed out.')
clearTimeout(timer);
server.close();
}, 3000); // <- timeout
server.onopen = () => {
clearTimeout(timer);
if (tries > 0) {
console.log(`Reconnected after ${tries} tries`)
overlay.set({
show: false,
closable: true,
style: '',
message: ''
})
send('register', {
recovery: localStorage.getItem('recovery')
});
} else {
console.log('Connected!')
}
resolve(server);
};
server.onerror = (err) => {
console.log('Socket errored');
reject(err);
};
server.onmessage = (event) => {
receive(JSON.parse(event.data))
};
let closing = false;
window.onbeforeunload = () => {
closing = true;
};
server.onclose = () => {
console.log('Socket closed!')
overlay.set({
show: true,
closable: false,
style: 'error',
message: 'Womp womp. The server just went offline! You\'ll be reconnected as soon as possible' + '.'.repeat(tries)
})
if (!closing) setTimeout(() => connect(tries + 1), tries < 10 ? 3000 : 10000);
};
});
}