aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib')
-rw-r--r--src/lib/socket.js29
-rw-r--r--src/lib/store.js1
-rw-r--r--src/lib/utils.js8
3 files changed, 22 insertions, 16 deletions
diff --git a/src/lib/socket.js b/src/lib/socket.js
index efc2651b..9d0c472e 100644
--- a/src/lib/socket.js
+++ b/src/lib/socket.js
@@ -1,8 +1,17 @@
-import { get } from "svelte/store";
-import { rate, user, token, ws } from '$lib/store';
+import { get } from 'svelte/store';
+import { rate, user, token } from '$lib/store';
let interval, socket;
+export const auth = () => {
+ let t = get(token);
+ if (t) send('login', t);
+};
+
+export const send = (type, data) => {
+ socket?.readyState === 1 && socket.send(JSON.stringify({ type, data }));
+};
+
export const messages = (data) => ({
rate() {
rate.set(data);
@@ -12,9 +21,7 @@ export const messages = (data) => ({
console.log(data);
},
- connected() {
- socket.send(JSON.stringify({ type: 'login', data: { token: get(token) } }));
- },
+ connected: auth,
login() {
user.set(data);
@@ -29,18 +36,14 @@ let currentReconnectDelay = initialReconnectDelay;
export function connect() {
clearInterval(interval);
- if (socket) socket.close();
+ if (socket) return auth();
+
socket = new WebSocket('ws://localhost:3119/ws');
socket.addEventListener('open', onWebsocketOpen);
socket.addEventListener('close', onWebsocketClose);
socket.addEventListener('message', onWebsocketMessage);
- interval = setInterval(
- () => socket.readyState === 1 && socket.send(JSON.stringify({ type: 'heartbeat' })),
- 5000
- );
-
- ws.set(socket);
+ interval = setInterval(() => send('heartbeat'), 5000);
}
function onWebsocketMessage(msg) {
@@ -53,7 +56,7 @@ function onWebsocketOpen() {
}
function onWebsocketClose() {
- ws.set(null);
+ socket = null;
setTimeout(() => {
reconnectToWebsocket();
}, currentReconnectDelay + Math.floor(Math.random() * 3000));
diff --git a/src/lib/store.js b/src/lib/store.js
index 3963f55a..94b7fffd 100644
--- a/src/lib/store.js
+++ b/src/lib/store.js
@@ -3,4 +3,3 @@ import { writable } from 'svelte/store';
export const rate = writable();
export const user = writable();
export const token = writable();
-export const ws = writable();
diff --git a/src/lib/utils.js b/src/lib/utils.js
index 595d2dd8..b1bc24ec 100644
--- a/src/lib/utils.js
+++ b/src/lib/utils.js
@@ -1,10 +1,14 @@
+import { browser } from "$app/env";
+
export function scroll(section) {
section.scrollIntoView({ behavior: 'smooth' });
}
+const base = browser ? "" : import.meta.env.VITE_COINOS_URL;
+
export const post = (url, body) =>
- fetch(url, {
+ fetch(base + url, {
method: 'POST',
body: JSON.stringify(body),
headers: { 'accept': 'application/json', 'content-type': 'application/json' }
- });
+ }).then(r => r.json);