lazy load socket connection

This commit is contained in:
Fran Jurmanović
2025-09-21 22:53:23 +02:00
parent 3ba83ad538
commit 6aeb654abf
18 changed files with 216 additions and 572 deletions

View File

@@ -1,5 +1,7 @@
'use client';
import { SessionData } from '@/lib/session/config';
const BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8080';
export type ClientApiResponse<T> = {
@@ -8,6 +10,17 @@ export type ClientApiResponse<T> = {
message?: string;
};
const getSession = async (): Promise<SessionData | null> => {
const response = await fetch('/api/session');
if (response.ok) {
return await response.json();
}
return null;
};
const destroySession = async (): Promise<void> => {
await fetch('/api/session', { method: 'DELETE' });
};
export async function fetchClientAPI<T>(
endpoint: string,
method: string = 'GET',
@@ -15,13 +28,11 @@ export async function fetchClientAPI<T>(
customToken?: string
): Promise<ClientApiResponse<T>> {
let token = customToken;
let session: SessionData | null = null;
if (!token) {
const response = await fetch('/api/session');
if (response.ok) {
const session = await response.json();
token = session.openToken;
}
session = await getSession();
token = session?.openToken;
if (!token) {
throw new Error('No authentication token available');
@@ -41,7 +52,8 @@ export async function fetchClientAPI<T>(
if (!response.ok) {
if (response.status === 401) {
window.location.href = '/logout';
await destroySession();
window.location.href = '/login';
return { error: 'unauthorized' };
}
throw new Error(`API Error: ${response.statusText} - ${method} - ${BASE_URL}${endpoint}`);

View File

@@ -1,5 +1,3 @@
import { redirect } from 'next/navigation';
const BASE_URL = process.env.API_BASE_URL || 'http://localhost:8080';
type ApiResponse<T> = {
@@ -8,6 +6,10 @@ type ApiResponse<T> = {
message?: string;
};
const destroySession = async (): Promise<void> => {
await fetch('/api/session', { method: 'DELETE' });
};
export async function fetchServerAPI<T>(
endpoint: string,
token: string,
@@ -28,7 +30,8 @@ export async function fetchServerAPI<T>(
if (!response.ok) {
if (response.status == 401) {
redirect('/logout');
await destroySession();
window.location.href = '/login';
return { error: 'unauthorized' };
}
throw new Error(