Dynavera/src/lib/api.ts
Viswamedha Nalabotu 03490762be Fixed core issues
2025-12-20 20:40:23 +00:00

77 lines
2.2 KiB
TypeScript

import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
class ApiClient {
private client: AxiosInstance;
constructor() {
this.client = axios.create({ withCredentials: true });
}
private getCsrfToken(): string {
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;
}
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';