66 lines
2.0 KiB
TypeScript
66 lines
2.0 KiB
TypeScript
import axios, { AxiosInstance } 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: (...args: Parameters<AxiosInstance["get"]>) => {
|
|
if (!_api) throw new Error("API client not initialized");
|
|
return _api.get(...args);
|
|
},
|
|
post: (...args: Parameters<AxiosInstance["post"]>) => {
|
|
if (!_api) throw new Error("API client not initialized");
|
|
return _api.post(...args);
|
|
},
|
|
put: (...args: Parameters<AxiosInstance["put"]>) => {
|
|
if (!_api) throw new Error("API client not initialized");
|
|
return _api.put(...args);
|
|
},
|
|
delete: (...args: Parameters<AxiosInstance["delete"]>) => {
|
|
if (!_api) throw new Error("API client not initialized");
|
|
return _api.delete(...args);
|
|
},
|
|
};
|
|
|
|
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));
|
|
}
|