import axios, { type AxiosError, AxiosHeaders } from 'axios'; import type { ApiContext, ApiError, ApiErrorData } from './types'; import { encodeWafNormalizer } from './paramsSerializer/encodeWafNormalizer'; export async function usePublicApi< ResponseType, FieldOptions = '', OrderOptions = '', ConditionOptions = '', >( apiContext: ApiContext, ): Promise; export async function usePublicApi< ResponseType, RequestType = object, FieldOptions = '', OrderOptions = FieldOptions, ConditionOptions = FieldOptions, >({ endpoint, method = 'GET', payload, params, }: ApiContext) { const headers = new AxiosHeaders({ 'Uappi-Cookie-Name': 'token', Accept: 'application/json', }); if ( window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1' ) headers.set('uappi-environment', 'development'); const axiosInstance = axios.create({ baseURL: `${window.location.protocol}//${window.location.host}/api/v3`, headers, paramsSerializer: { encode: encodeWafNormalizer, }, }); return axiosInstance<{ data: ResponseType; status: boolean }>(endpoint, { method, data: payload || undefined, params, withCredentials: true, }) .then(({ data }) => { return data.data; }) .catch(e => { const axiosError = e as AxiosError; const apiErrorData = ( axiosError.response!.data as { data: ApiErrorData; status: boolean } ).data; throw { message: apiErrorData.message || '', errorCode: apiErrorData.errorCode, status: axiosError.status, } as ApiError; }); }