axios & api'
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
import { apiClient } from "./axios.instance";
|
||||
import type { AxiosResponse } from "axios";
|
||||
|
||||
export interface ApiResponse<T = any> {
|
||||
data: T;
|
||||
message: string;
|
||||
success: boolean;
|
||||
}
|
||||
|
||||
class ApiService {
|
||||
async get<T>(url: string, config?: any): Promise<T> {
|
||||
const response: AxiosResponse<T> = await apiClient.get(url, config);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
async post<T, D = any>(url: string, data?: D, config?: any): Promise<T> {
|
||||
const response: AxiosResponse<T> = await apiClient.post(url, data, config);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
async put<T, D = any>(url: string, data?: D, config?: any): Promise<T> {
|
||||
const response: AxiosResponse<T> = await apiClient.put(url, data, config);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
async patch<T, D = any>(url: string, data?: D, config?: any): Promise<T> {
|
||||
const response: AxiosResponse<T> = await apiClient.patch(url, data, config);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
async delete<T>(url: string, config?: any): Promise<T> {
|
||||
const response: AxiosResponse<T> = await apiClient.delete(url, config);
|
||||
return response.data;
|
||||
}
|
||||
}
|
||||
|
||||
export const apiService = new ApiService();
|
||||
@@ -0,0 +1,104 @@
|
||||
import axios, {
|
||||
type AxiosInstance,
|
||||
type AxiosResponse,
|
||||
type AxiosError,
|
||||
type InternalAxiosRequestConfig,
|
||||
} from "axios";
|
||||
|
||||
export interface ApiResponse<T = any> {
|
||||
data: T;
|
||||
message?: string;
|
||||
status: number;
|
||||
}
|
||||
|
||||
class ApiClient {
|
||||
private axiosInstance: AxiosInstance;
|
||||
|
||||
constructor() {
|
||||
this.axiosInstance = axios.create({
|
||||
baseURL: "http://213.165.213.170:8080/api/v1",
|
||||
timeout: 10000,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
validateStatus: (status) => {
|
||||
return status >= 200 && status < 400;
|
||||
},
|
||||
// Добавляем кастомный сериализатор параметров
|
||||
paramsSerializer: {
|
||||
serialize: (params) => {
|
||||
const parts: string[] = [];
|
||||
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
if (value === undefined || value === null) return;
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
// Преобразуем массив в множественные параметры: level=info&level=warning
|
||||
value.forEach((item) => {
|
||||
if (item !== undefined && item !== null) {
|
||||
parts.push(
|
||||
`${encodeURIComponent(key)}=${encodeURIComponent(item)}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
parts.push(
|
||||
`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return parts.join("&");
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
this.setupInterceptors();
|
||||
}
|
||||
|
||||
private setupInterceptors(): void {
|
||||
this.axiosInstance.interceptors.request.use(
|
||||
(config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
|
||||
// Получаем токен из localStorage
|
||||
const authStorage = localStorage.getItem("auth-storage");
|
||||
if (authStorage) {
|
||||
try {
|
||||
const parsed = JSON.parse(authStorage);
|
||||
const token = parsed.state?.token;
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[Auth] Failed to parse auth storage:", e);
|
||||
}
|
||||
}
|
||||
return config;
|
||||
},
|
||||
(error: AxiosError): Promise<AxiosError> => {
|
||||
console.error("[Request Error]", error);
|
||||
return Promise.reject(error);
|
||||
},
|
||||
);
|
||||
|
||||
this.axiosInstance.interceptors.response.use(
|
||||
(response: AxiosResponse): AxiosResponse => {
|
||||
console.log(`[Response] ${response.status} ${response.config.url}`);
|
||||
return response;
|
||||
},
|
||||
async (error: AxiosError): Promise<any> => {
|
||||
if (error.response?.status === 401) {
|
||||
window.location.href = "/auth";
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
return Promise.reject(error);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
public getInstance(): AxiosInstance {
|
||||
return this.axiosInstance;
|
||||
}
|
||||
}
|
||||
|
||||
export const apiClient = new ApiClient().getInstance();
|
||||
@@ -0,0 +1,32 @@
|
||||
import { useState, useCallback } from "react";
|
||||
|
||||
export function useApi() {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const request = useCallback(
|
||||
async <T>(apiCall: () => Promise<T>): Promise<T | undefined> => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await apiCall();
|
||||
return result;
|
||||
} catch (err: any) {
|
||||
const errorMessage =
|
||||
err.response?.data?.message || err.message || "Произошла ошибка";
|
||||
setError(errorMessage);
|
||||
return undefined;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return {
|
||||
isLoading,
|
||||
error,
|
||||
request,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { apiClient } from "./axios.instance";
|
||||
export { useApi } from "./hooks/use.api";
|
||||
Reference in New Issue
Block a user