migrate to nextjs
This commit is contained in:
73
src/lib/api/client/hooks.ts
Normal file
73
src/lib/api/client/hooks.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
'use client';
|
||||
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
async function fetchFromAPI(endpoint: string, method: string = 'GET', body?: unknown) {
|
||||
const response = await fetch(endpoint, {
|
||||
method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: body ? JSON.stringify(body) : undefined
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`API Error: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export function useServerStatus(serverId: string) {
|
||||
return useQuery({
|
||||
queryKey: ['server-status', serverId],
|
||||
queryFn: () => fetchFromAPI(`/api/server/${serverId}/status`),
|
||||
refetchInterval: 30000
|
||||
});
|
||||
}
|
||||
|
||||
export function useServerAction(serverId: string) {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ action }: { action: 'start' | 'stop' | 'restart' }) =>
|
||||
fetchFromAPI(`/api/server/${serverId}/action`, 'POST', { action }),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['server-status', serverId] });
|
||||
queryClient.invalidateQueries({ queryKey: ['servers'] });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function useUsers(params?: Record<string, string>) {
|
||||
const searchParams = new URLSearchParams(params).toString();
|
||||
const endpoint = `/api/membership${searchParams ? `?${searchParams}` : ''}`;
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['users', params],
|
||||
queryFn: () => fetchFromAPI(endpoint)
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateUser() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (userData: { username: string; password: string; role: string }) =>
|
||||
fetchFromAPI('/api/membership', 'POST', userData),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['users'] });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteUser() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (userId: string) => fetchFromAPI(`/api/membership/${userId}`, 'DELETE'),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['users'] });
|
||||
}
|
||||
});
|
||||
}
|
||||
12
src/lib/api/client/query-client.ts
Normal file
12
src/lib/api/client/query-client.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
'use client';
|
||||
|
||||
import { QueryClient } from '@tanstack/react-query';
|
||||
|
||||
export const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 5 * 60 * 1000,
|
||||
refetchOnWindowFocus: false
|
||||
}
|
||||
}
|
||||
});
|
||||
30
src/lib/api/server/auth.ts
Normal file
30
src/lib/api/server/auth.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { User } from '@/lib/types';
|
||||
import { fetchServerAPI } from './base';
|
||||
|
||||
const BASE_URL = process.env.API_BASE_URL || 'http://localhost:8080';
|
||||
|
||||
const authRoute = '/auth';
|
||||
|
||||
export async function loginUser(username: string, password: string) {
|
||||
const response = await fetch(`${BASE_URL}${authRoute}/login`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ username, password })
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Login failed: ${response.statusText} - ${BASE_URL}${authRoute}/login`);
|
||||
}
|
||||
|
||||
const { token } = await response.json();
|
||||
|
||||
const userResponse = await getCurrentUser(token);
|
||||
|
||||
return { token, user: userResponse };
|
||||
}
|
||||
|
||||
export async function getCurrentUser(token: string) {
|
||||
return fetchServerAPI<User>(`${authRoute}/me`, token);
|
||||
}
|
||||
31
src/lib/api/server/base.ts
Normal file
31
src/lib/api/server/base.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
const BASE_URL = process.env.API_BASE_URL || 'http://localhost:8080';
|
||||
|
||||
export async function fetchServerAPI<T>(
|
||||
endpoint: string,
|
||||
token: string,
|
||||
method: string = 'GET',
|
||||
body?: object
|
||||
): Promise<T> {
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${token}`
|
||||
};
|
||||
|
||||
const response = await fetch(`${BASE_URL}${endpoint}`, {
|
||||
method,
|
||||
headers,
|
||||
body: body ? JSON.stringify(body) : undefined
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`API Error: ${response.statusText} - ${method} - ${BASE_URL}${endpoint} - ${token}`
|
||||
);
|
||||
}
|
||||
|
||||
if (response.headers.get('Content-Type')?.includes('application/json')) {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
return response.text() as T;
|
||||
}
|
||||
40
src/lib/api/server/configuration.ts
Normal file
40
src/lib/api/server/configuration.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { fetchServerAPI } from './base';
|
||||
import type {
|
||||
Configurations,
|
||||
Configuration,
|
||||
AssistRules,
|
||||
EventConfig,
|
||||
EventRules,
|
||||
ServerSettings,
|
||||
ConfigFile
|
||||
} from '@/lib/types/config';
|
||||
|
||||
const serverRoute = '/server';
|
||||
|
||||
export async function getServerConfigurations(
|
||||
token: string,
|
||||
serverId: string
|
||||
): Promise<Configurations> {
|
||||
return fetchServerAPI<Configurations>(`${serverRoute}/${serverId}/config`, token);
|
||||
}
|
||||
|
||||
export async function getServerConfiguration(
|
||||
token: string,
|
||||
serverId: string,
|
||||
configType: ConfigFile
|
||||
): Promise<Configuration | AssistRules | EventConfig | EventRules | ServerSettings> {
|
||||
return fetchServerAPI(`${serverRoute}/${serverId}/config/${configType}`, token);
|
||||
}
|
||||
|
||||
export async function updateServerConfiguration(
|
||||
token: string,
|
||||
serverId: string,
|
||||
configType: ConfigFile,
|
||||
config: Configuration | AssistRules | EventConfig | EventRules | ServerSettings,
|
||||
restart = false
|
||||
): Promise<void> {
|
||||
await fetchServerAPI(`${serverRoute}/${serverId}/config/${configType}`, token, 'PUT', {
|
||||
...config,
|
||||
restart
|
||||
});
|
||||
}
|
||||
24
src/lib/api/server/lookups.ts
Normal file
24
src/lib/api/server/lookups.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { fetchServerAPI } from './base';
|
||||
import { Track, CarModel, CupCategory, DriverCategory, SessionType } from '@/lib/types';
|
||||
|
||||
const lookupRoute = '/lookup';
|
||||
|
||||
export async function getTracks(token: string): Promise<Track[]> {
|
||||
return fetchServerAPI(`${lookupRoute}/tracks`, token);
|
||||
}
|
||||
|
||||
export async function getCarModels(token: string): Promise<CarModel[]> {
|
||||
return fetchServerAPI(`${lookupRoute}/car-models`, token);
|
||||
}
|
||||
|
||||
export async function getCupCategories(token: string): Promise<CupCategory[]> {
|
||||
return fetchServerAPI(`${lookupRoute}/cup-categories`, token);
|
||||
}
|
||||
|
||||
export async function getDriverCategories(token: string): Promise<DriverCategory[]> {
|
||||
return fetchServerAPI(`${lookupRoute}/driver-categories`, token);
|
||||
}
|
||||
|
||||
export async function getSessionTypes(token: string): Promise<SessionType[]> {
|
||||
return fetchServerAPI(`${lookupRoute}/session-types`, token);
|
||||
}
|
||||
51
src/lib/api/server/membership.ts
Normal file
51
src/lib/api/server/membership.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { fetchServerAPI } from './base';
|
||||
import { User, Role } from '@/lib/types';
|
||||
|
||||
export interface UserListParams {
|
||||
username?: string;
|
||||
role_name?: string;
|
||||
sort_by?: string;
|
||||
sort_desc?: boolean;
|
||||
page?: number;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
const membershipRoute = '/membership';
|
||||
|
||||
export async function getUsers(token: string, params: UserListParams = {}): Promise<User[]> {
|
||||
const searchParams = new URLSearchParams();
|
||||
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
if (value !== undefined) {
|
||||
searchParams.set(key, value.toString());
|
||||
}
|
||||
});
|
||||
|
||||
const queryString = searchParams.toString();
|
||||
const endpoint = `${membershipRoute}${queryString ? `?${queryString}` : ''}`;
|
||||
|
||||
return fetchServerAPI(endpoint, token);
|
||||
}
|
||||
|
||||
export async function createUser(
|
||||
token: string,
|
||||
userData: { username: string; password: string; role: string }
|
||||
) {
|
||||
return fetchServerAPI(membershipRoute, token, 'POST', userData);
|
||||
}
|
||||
|
||||
export async function getUserById(token: string, userId: string): Promise<User> {
|
||||
return fetchServerAPI(`${membershipRoute}/${userId}`, token);
|
||||
}
|
||||
|
||||
export async function updateUser(token: string, userId: string, userData: Partial<User>) {
|
||||
return fetchServerAPI(`${membershipRoute}/${userId}`, token, 'PUT', userData);
|
||||
}
|
||||
|
||||
export async function deleteUser(token: string, userId: string) {
|
||||
return fetchServerAPI(`${membershipRoute}/${userId}`, token, 'DELETE');
|
||||
}
|
||||
|
||||
export async function getRoles(token: string): Promise<Role[]> {
|
||||
return fetchServerAPI(`${membershipRoute}/roles`, token);
|
||||
}
|
||||
30
src/lib/api/server/servers.ts
Normal file
30
src/lib/api/server/servers.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { fetchServerAPI } from './base';
|
||||
import { Server } from '@/lib/types/server';
|
||||
|
||||
const serverRoute = '/server';
|
||||
|
||||
export async function getServers(token: string): Promise<Server[]> {
|
||||
const response = await fetchServerAPI<Server[]>(serverRoute, token);
|
||||
return response;
|
||||
}
|
||||
|
||||
export async function getServer(token: string, serverId: string): Promise<Server> {
|
||||
const response = await fetchServerAPI<Server>(`${serverRoute}/${serverId}`, token);
|
||||
return response;
|
||||
}
|
||||
|
||||
export async function restartService(token: string, serverId: string) {
|
||||
return fetchServerAPI(`${serverRoute}/${serverId}/service/restart`, token, 'POST');
|
||||
}
|
||||
|
||||
export async function startService(token: string, serverId: string) {
|
||||
return fetchServerAPI(`${serverRoute}/${serverId}/service/start`, token, 'POST');
|
||||
}
|
||||
|
||||
export async function stopService(token: string, serverId: string) {
|
||||
return fetchServerAPI(`${serverRoute}/${serverId}/service/stop`, token, 'POST');
|
||||
}
|
||||
|
||||
export async function getServiceStatus(token: string, serverId: string) {
|
||||
return fetchServerAPI(`${serverRoute}/${serverId}/service`, token);
|
||||
}
|
||||
16
src/lib/api/server/statistics.ts
Normal file
16
src/lib/api/server/statistics.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { fetchServerAPI } from './base';
|
||||
import type { StateHistoryStats } from '@/lib/types/statistics';
|
||||
|
||||
const serverRoute = '/server';
|
||||
|
||||
export async function getServerStatistics(
|
||||
token: string,
|
||||
serverId: string,
|
||||
startDate: string,
|
||||
endDate: string
|
||||
): Promise<StateHistoryStats> {
|
||||
return fetchServerAPI<StateHistoryStats>(
|
||||
`${serverRoute}/${serverId}/state-history/statistics?start_date=${startDate}&end_date=${endDate}`,
|
||||
token
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user