71 lines
2.5 KiB
TypeScript
71 lines
2.5 KiB
TypeScript
import axios, { AxiosInstance } from "axios";
|
|
import type { AxiosResponse } from "axios";
|
|
import { createApiClient } from "../../react-auth";
|
|
|
|
/**
|
|
* We expose a singleton-like getter/setter for the API clients
|
|
*/
|
|
let _api: AxiosInstance | null = null;
|
|
let _auth: AxiosInstance | null = null;
|
|
|
|
function withParamsSerializer(instance: AxiosInstance): AxiosInstance {
|
|
instance.defaults.paramsSerializer = {
|
|
serialize: (params) => {
|
|
const searchParams = new URLSearchParams();
|
|
|
|
Object.entries(params).forEach(([key, value]) => {
|
|
if (Array.isArray(value)) {
|
|
value.forEach((v) => {
|
|
searchParams.append(key, String(v)); // NO []
|
|
});
|
|
} else if (value !== undefined && value !== null) {
|
|
searchParams.append(key, String(value));
|
|
}
|
|
});
|
|
|
|
return searchParams.toString();
|
|
},
|
|
};
|
|
|
|
return instance;
|
|
}
|
|
|
|
export const api = {
|
|
get: <T = any, R = AxiosResponse<T>>(url: string, config?: Parameters<AxiosInstance["get"]>[1]) => {
|
|
if (!_api) throw new Error("API client not initialized");
|
|
return _api.get<T, R>(url, config);
|
|
},
|
|
post: <T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: Parameters<AxiosInstance["post"]>[2]) => {
|
|
if (!_api) throw new Error("API client not initialized");
|
|
return _api.post<T, R>(url, data, config);
|
|
},
|
|
put: <T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: Parameters<AxiosInstance["put"]>[2]) => {
|
|
if (!_api) throw new Error("API client not initialized");
|
|
return _api.put<T, R>(url, data, config);
|
|
},
|
|
delete: <T = any, R = AxiosResponse<T>>(url: string, config?: Parameters<AxiosInstance["delete"]>[1]) => {
|
|
if (!_api) throw new Error("API client not initialized");
|
|
return _api.delete<T, R>(url, config);
|
|
},
|
|
patch: <T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: Parameters<AxiosInstance["patch"]>[2]) => {
|
|
if (!_api) throw new Error("API client not initialized");
|
|
return _api.patch<T, R>(url, data, config);
|
|
},
|
|
};
|
|
|
|
export const auth = {
|
|
post: (...args: Parameters<AxiosInstance["post"]>) => {
|
|
if (!_auth) throw new Error("Auth client not initialized");
|
|
return _auth.post(...args);
|
|
},
|
|
get: (...args: Parameters<AxiosInstance["get"]>) => {
|
|
if (!_auth) throw new Error("Auth client not initialized");
|
|
return _auth.get(...args);
|
|
},
|
|
};
|
|
|
|
export function initializeApiClients(baseUrl: string, authBaseUrl: string) {
|
|
_api = withParamsSerializer(createApiClient(baseUrl));
|
|
_auth = withParamsSerializer(createApiClient(authBaseUrl));
|
|
}
|