Return token promise instead of token, speeds up page loading a lot

This commit is contained in:
Neshura 2024-01-03 23:59:15 +01:00
parent fbe9f89c0f
commit 3b017673b3
Signed by: Neshura
GPG key ID: B6983AAA6B9A7A6C
2 changed files with 56 additions and 20 deletions

View file

@ -1,27 +1,61 @@
import { io } from 'socket.io-client';
import { io, Socket } from 'socket.io-client';
import * as fs from 'fs';
export async function load() {
const credFile = './credentials.json';
const promise = getJwt();
return {
promise
};
}
async function getJwt(): Promise<string> {
const socket = io('https://status.neshweb.net/');
const credFile = './credentials.json';
let token = '';
let valid = false;
socket.on('connect', () => {
if (fs.existsSync(credFile)) {
const content = fs.readFileSync(credFile);
token = content.toString();
}
socket.on('connect', async () => {
if (token == '') {
token = await login(socket);
valid = true;
} else {
socket.emit('loginByToken', token, async (res) => {
if (!res.ok) {
token = await login(socket);
}
valid = true;
});
}
});
while (!valid) {
await new Promise((resolve) => setTimeout(resolve, 10));
}
fs.writeFileSync(credFile, token);
return token;
}
async function login(socket: Socket): Promise<string> {
let token = '';
socket.emit(
'login',
{ username: process.env.KUMA_USERNAME, password: process.env.KUMA_PASSWORD, token: '' },
(res) => {
(res: { token: string }) => {
token = res.token;
}
);
});
while (token == '') {
await new Promise((resolve) => setTimeout(resolve, 10));
}
return {
token
};
return token;
}

View file

@ -6,11 +6,13 @@
import { io } from 'socket.io-client';
import type { Heartbeat } from '$lib/types/uptime-kuma-types';
let { data }: { data: { token: string } } = $props();
let { data }: { data: { promise: Promise<string> } } = $props();
$effect(() => {
console.log('Data:', data.token);
});
let token = $state();
data.promise.then((jwt) => {
token = jwt;
})
let services: readonly Service[] = $state.frozen([]);
@ -21,11 +23,11 @@
//let token = $props();
$effect(() => {
if (data.token) {
if (token) {
const socket = io('https://status.neshweb.net/');
socket.on('connect', () => {
socket.emit('loginByToken', data.token, (res) => {
socket.emit('loginByToken', token, () => {
});
});