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'; import * as fs from 'fs';
export async function load() { 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 socket = io('https://status.neshweb.net/');
const credFile = './credentials.json';
let token = ''; let token = '';
let valid = false;
socket.on('connect', () => { if (fs.existsSync(credFile)) {
socket.emit( const content = fs.readFileSync(credFile);
'login', token = content.toString();
{ username: process.env.KUMA_USERNAME, password: process.env.KUMA_PASSWORD, token: '' }, }
(res) => {
token = res.token; 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: { token: string }) => {
token = res.token;
}
);
while (token == '') { while (token == '') {
await new Promise((resolve) => setTimeout(resolve, 10)); await new Promise((resolve) => setTimeout(resolve, 10));
} }
return { return token;
token
};
} }

View file

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