68 lines
1.8 KiB
TypeScript
68 lines
1.8 KiB
TypeScript
|
|
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
|
||
|
|
|
||
|
|
class ApiClient {
|
||
|
|
private client: AxiosInstance;
|
||
|
|
|
||
|
|
constructor() {
|
||
|
|
this.client = axios.create({ withCredentials: true });
|
||
|
|
}
|
||
|
|
|
||
|
|
private getCsrfToken(): string {
|
||
|
|
const match = document.cookie.match(/(?:^|; )csrftoken=([^;]+)/);
|
||
|
|
return match ? decodeURIComponent(match[1]) : '';
|
||
|
|
}
|
||
|
|
|
||
|
|
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';
|