This commit is contained in:
Mikan
2025-05-30 19:32:58 +03:00
parent 93471d038a
commit 90d12b57ec
25 changed files with 3395 additions and 180 deletions

113
src/API/common.ts Normal file
View File

@@ -0,0 +1,113 @@
import {useEffect, useState} from "react";
import {DEBUG_MODE} from "../utils/common";
import {ApiResponse, PageResponse} from "../types/api.ts";
import {PageControl} from "../types/common.ts";
export function hostUrl(url: string){
return DEBUG_MODE? "http://localhost:8000"+url: url;
}
export function apiUrl(url: string) {
return hostUrl("/api/v1"+url);
}
export async function getFetch(path:string) {
try{
const response = await fetch(
apiUrl(path), {
method: "GET",
credentials: "include"
}
);
if (!response.ok){
const body = await response.json();
console.error('Error fetching:', 'Network response was not ok', body);
return {
body: body,
success: false
} as ApiResponse;
}
return {
body: await response.json(),
success: true,
} as ApiResponse
}
catch {
return {
success: false
} as ApiResponse;
}
}
export function useDataPage<T>(application:string, endpoint: string) {
const [data, setData] = useState<T[]|null>(null);
// const [previousUrl, setPreviousUrl] = useState<string|undefined>(undefined)
// const [nextUrl, setNextUrl] = useState<string|undefined>(undefined)
useEffect(
()=>{
if (data === null){
getFetch(`/${application}/${endpoint}/`).then((r)=>{
if (r.success){
const pageData = r.body as PageResponse<T>;
setData(pageData.results);
}
else {
setData([]);
}
})
}
},
[data, application, endpoint]
)
// function changePage(pageUrl: string|undefined) {
// if (pageUrl){ //TODO CHANGING PAGES
// getFetch(`/${application}/${endpoint}/`).then((r)=>{
// if (r.success){
// const pageData = r.body as PageResponse<T>;
//
// setData(pageData.results);
//
//
// }
// })
// }
// }
function nextPage() {
// changePage(nextUrl)
}
function previousPage() {
// changePage(previousUrl)
}
return {
items: data,
hasPrevious: undefined,//previousUrl !== undefined,
hasNext: undefined,//nextUrl !== undefined,
nextPage,
previousPage
} as PageControl<T>
}

View File

@@ -0,0 +1 @@