Auth
This commit is contained in:
@@ -1,187 +1,122 @@
|
||||
import {useEffect, useMemo, useState} from "react";
|
||||
import {DEBUG_MODE} from "../utils/common";
|
||||
import {ApiResponse, PageResponse} from "../types/api.ts";
|
||||
import {PageControl} from "../types/common.ts";
|
||||
import {Institution} from "../types/survey.ts";
|
||||
|
||||
export function hostUrl(url: string){
|
||||
return DEBUG_MODE? "http://localhost:8000"+url: url;
|
||||
}
|
||||
|
||||
export function apiUrl(url: string) {
|
||||
return hostUrl("/api/v1"+url);
|
||||
}
|
||||
import {apiUrl, getTokensFromCookies} from "../utils/common.ts";
|
||||
import {ApiResponse} from "../types/api.ts";
|
||||
|
||||
|
||||
export async function getFetch(path:string) {
|
||||
export async function getFetch(path: string): Promise<ApiResponse> {
|
||||
const finalTokens = getTokensFromCookies();
|
||||
|
||||
try{
|
||||
const response = await fetch(
|
||||
apiUrl(path), {
|
||||
method: "GET",
|
||||
credentials: "include"
|
||||
}
|
||||
);
|
||||
try {
|
||||
const response = await fetch(apiUrl(path), {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
...(finalTokens?.access && { Authorization: `Bearer ${finalTokens.access}` }),
|
||||
},
|
||||
credentials: "include"
|
||||
});
|
||||
|
||||
if (!response.ok){
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
const createQueryString = (params: Record<string, string | number | boolean | undefined>): string => {
|
||||
const filteredParams = Object.entries(params)
|
||||
.filter(([_, value]) => value !== undefined && value !== null)
|
||||
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
|
||||
return filteredParams.join('&');
|
||||
};
|
||||
|
||||
export function useDataPage<T>(application:string, endpoint: string, params:{[key:string]:string|number}={}, needLoad:boolean=true):PageControl<T> {
|
||||
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 && needLoad){
|
||||
getFetch(`/${application}/${endpoint}/?${createQueryString(params)}`).then((r)=>{
|
||||
if (r.success){
|
||||
const pageData = r.body as PageResponse<T>;
|
||||
|
||||
setData(pageData.results);
|
||||
|
||||
|
||||
}
|
||||
else {
|
||||
setData([]);
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
[data, application, endpoint, needLoad]
|
||||
)
|
||||
|
||||
// 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: false,//previousUrl !== undefined,
|
||||
hasNext: false,//nextUrl !== undefined,
|
||||
nextPage,
|
||||
previousPage
|
||||
} as PageControl<T>
|
||||
|
||||
|
||||
}
|
||||
|
||||
export function useData<T>(application:string, endpoint: string, id: string|number, needLoad:boolean=true): T|null|undefined {
|
||||
|
||||
const [data, setData] = useState<T | null | undefined>(null);
|
||||
|
||||
useEffect(
|
||||
()=>{
|
||||
if (data === null && needLoad){
|
||||
getFetch(`/${application}/${endpoint}/${id}`).then((r)=>{
|
||||
if (r.success){
|
||||
const pageData = r.body as T;
|
||||
setData(pageData);
|
||||
}
|
||||
else {
|
||||
setData(undefined);
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
[data, application, endpoint, id, needLoad]
|
||||
)
|
||||
|
||||
return data;
|
||||
|
||||
}
|
||||
|
||||
export function useCachedData<T>(application: string, endpoint: string) {
|
||||
const [cache, setCache] = useState<Map<string | number, T | undefined>>(new Map());
|
||||
|
||||
useEffect(() => {
|
||||
// Очистка кеша или другие побочные эффекты при необходимости
|
||||
return () => {
|
||||
setCache(new Map());
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (id: string | number, needLoad: boolean = true): T | undefined | null => {
|
||||
const cachedData = cache.has(id)?cache.get(id):null;
|
||||
|
||||
if (cachedData !== null) {
|
||||
return cachedData;
|
||||
return { body, success: false };
|
||||
}
|
||||
|
||||
if (needLoad) {
|
||||
getFetch(`/${application}/${endpoint}/${id}`).then((r) => {
|
||||
if (r.success) {
|
||||
const data = r.body as T;
|
||||
setCache((prevCache) => {
|
||||
const newCache = new Map(prevCache);
|
||||
newCache.set(id, data);
|
||||
return newCache;
|
||||
});
|
||||
} else {
|
||||
setCache((prevCache) => {
|
||||
const newCache = new Map(prevCache);
|
||||
newCache.set(id, undefined);
|
||||
return newCache;
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
return { body: await response.json(), success: true };
|
||||
} catch (error) {
|
||||
console.error('Error fetching:', error);
|
||||
return { success: false };
|
||||
}
|
||||
}
|
||||
|
||||
export async function postFetch(
|
||||
path: string,
|
||||
body: object | FormData
|
||||
): Promise<ApiResponse> {
|
||||
const finalTokens = getTokensFromCookies();
|
||||
const isFormData = body instanceof FormData;
|
||||
|
||||
try {
|
||||
|
||||
const headers = new Headers();
|
||||
|
||||
if (finalTokens?.access){
|
||||
headers.append("Authorization", `Bearer ${finalTokens.access}`)
|
||||
}
|
||||
if (!isFormData){
|
||||
headers.append('Content-Type','application/json')
|
||||
}
|
||||
const response = await fetch(apiUrl(path), {
|
||||
method: 'POST',
|
||||
headers: headers,
|
||||
body: isFormData ? body as FormData : JSON.stringify(body),
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const responseBody = await response.json();
|
||||
console.error('Error posting:', 'Network response was not ok', responseBody);
|
||||
return { body: responseBody, success: false };
|
||||
}
|
||||
|
||||
return { body: await response.json(), success: true };
|
||||
} catch (error) {
|
||||
console.error('Error posting:', error);
|
||||
return { success: false };
|
||||
}
|
||||
}
|
||||
|
||||
export async function patchFetch(
|
||||
path: string,
|
||||
body: object | FormData
|
||||
): Promise<ApiResponse> {
|
||||
const finalTokens = getTokensFromCookies();
|
||||
const isFormData = body instanceof FormData;
|
||||
|
||||
try {
|
||||
const response = await fetch(apiUrl(path), {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
...(finalTokens?.access && { Authorization: `Bearer ${finalTokens.access}` }),
|
||||
...(!isFormData && { 'Content-Type': 'application/json' }),
|
||||
},
|
||||
body: isFormData ? body as FormData : JSON.stringify(body),
|
||||
credentials: 'include',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const responseBody = await response.json();
|
||||
console.error('Error patching:', 'Network response was not ok', responseBody);
|
||||
return { body: responseBody, success: false };
|
||||
}
|
||||
|
||||
return { body: await response.json(), success: true };
|
||||
} catch (error) {
|
||||
console.error('Error patching:', error);
|
||||
return { success: false };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export async function deleteFetch(path: string): Promise<ApiResponse> {
|
||||
const finalTokens = getTokensFromCookies();
|
||||
|
||||
try {
|
||||
const response = await fetch(apiUrl(path), {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
...(finalTokens?.access && { Authorization: `Bearer ${finalTokens.access}` }),
|
||||
},
|
||||
credentials: 'include',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const responseBody = await response.json();
|
||||
console.error('Error deleting:', 'Network response was not ok', responseBody);
|
||||
return { body: responseBody, success: false };
|
||||
}
|
||||
|
||||
return { body: await response.json(), success: true };
|
||||
} catch (error) {
|
||||
console.error('Error deleting:', error);
|
||||
return { success: false };
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user