2025-12-17 14:47:51 +00:00
|
|
|
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
|
|
|
|
|
|
|
|
|
|
class ApiClient {
|
|
|
|
|
private client: AxiosInstance;
|
|
|
|
|
|
|
|
|
|
constructor() {
|
|
|
|
|
this.client = axios.create({ withCredentials: true });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private getCsrfToken(): string {
|
2025-12-20 20:40:23 +00:00
|
|
|
let cookieValue = '';
|
|
|
|
|
if (document.cookie && document.cookie !== '') {
|
|
|
|
|
const cookies = document.cookie.split(';');
|
|
|
|
|
for (let i = 0; i < cookies.length; i++) {
|
|
|
|
|
const cookie = cookies[i].trim();
|
|
|
|
|
if (cookie.substring(0, 10) === 'csrftoken=') {
|
|
|
|
|
cookieValue = decodeURIComponent(cookie.substring(10));
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return cookieValue;
|
2025-12-17 14:47:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private withCsrf(config?: AxiosRequestConfig): AxiosRequestConfig {
|
|
|
|
|
const token = this.getCsrfToken();
|
|
|
|
|
const csrfHeader = token ? { 'X-CSRFToken': token } : {};
|
|
|
|
|
return {
|
|
|
|
|
...config,
|
|
|
|
|
headers: {
|
|
|
|
|
...csrfHeader,
|
|
|
|
|
...(config?.headers || {}),
|
|
|
|
|
},
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
get<T = unknown>(
|
|
|
|
|
url: string,
|
|
|
|
|
config?: AxiosRequestConfig
|
|
|
|
|
): Promise<AxiosResponse<T>> {
|
|
|
|
|
return this.client.get<T>(url, this.withCsrf(config));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
post<T = unknown>(
|
|
|
|
|
url: string,
|
|
|
|
|
data?: unknown,
|
|
|
|
|
config?: AxiosRequestConfig
|
|
|
|
|
): Promise<AxiosResponse<T>> {
|
|
|
|
|
return this.client.post<T>(url, data, this.withCsrf(config));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
put<T = unknown>(
|
|
|
|
|
url: string,
|
|
|
|
|
data?: unknown,
|
|
|
|
|
config?: AxiosRequestConfig
|
|
|
|
|
): Promise<AxiosResponse<T>> {
|
|
|
|
|
return this.client.put<T>(url, data, this.withCsrf(config));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
patch<T = unknown>(
|
|
|
|
|
url: string,
|
|
|
|
|
data?: unknown,
|
|
|
|
|
config?: AxiosRequestConfig
|
|
|
|
|
): Promise<AxiosResponse<T>> {
|
|
|
|
|
return this.client.patch<T>(url, data, this.withCsrf(config));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
delete<T = unknown>(
|
|
|
|
|
url: string,
|
|
|
|
|
config?: AxiosRequestConfig
|
|
|
|
|
): Promise<AxiosResponse<T>> {
|
|
|
|
|
return this.client.delete<T>(url, this.withCsrf(config));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const apiClient = new ApiClient();
|
|
|
|
|
export { isAxiosError } from 'axios';
|