aboutsummaryrefslogtreecommitdiffstats
path: root/db/db.js
Commit message (Expand)AuthorAgeFilesLines
* prod configAdam Soltys2022-09-221-11/+3
* prettierAdam Soltys2022-09-061-15/+11
* drop js extensionAdam Soltys2022-09-051-1/+1
* es6 migrationAdam Soltys2022-09-021-0/+17
='#n27'>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
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);
	},

	payment() {
		console.log(data, 'payment');
	},

	connected: auth,

	login() {
		user.set(data);
	}
});

const initialReconnectDelay = 1000;
const maxReconnectDelay = 16000;

let currentReconnectDelay = initialReconnectDelay;

export function connect() {
	clearInterval(interval);

	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(() => send('heartbeat'), 5000);
}

export function close() {
	if (socket) socket.close();
}

function onWebsocketMessage(msg) {
	let { type, data } = JSON.parse(msg.data);
	messages(data)[type] && messages(data)[type]();
}

function onWebsocketOpen() {
	currentReconnectDelay = initialReconnectDelay;
}

function onWebsocketClose() {
	socket = null;
	setTimeout(() => {
		reconnectToWebsocket();
	}, currentReconnectDelay + Math.floor(Math.random() * 3000));
}

function reconnectToWebsocket() {
	if (currentReconnectDelay < maxReconnectDelay) {
		currentReconnectDelay *= 2;
	}
	connect();
}