api.ts 849 B

12345678910111213141516171819202122232425262728293031323334
  1. import axios, { Method } from 'axios';
  2. import { useSytemStore } from '../state/systemStore';
  3. interface IFetchParams {
  4. endpoint: string;
  5. method?: Method;
  6. params?: JSON;
  7. data?: Record<string, unknown>;
  8. }
  9. const api = async <T = unknown>(fetchParams: IFetchParams): Promise<T> => {
  10. const { endpoint, method = 'GET', params, data } = fetchParams;
  11. const { getState } = useSytemStore;
  12. const BASE_URL = `http://${getState().internalIp}:3001`;
  13. const response = await axios.request<T & { error?: string }>({
  14. method,
  15. params,
  16. data,
  17. url: `${BASE_URL}${endpoint}`,
  18. withCredentials: true,
  19. });
  20. if (response.data.error) {
  21. throw new Error(response.data.error);
  22. }
  23. if (response.data) return response.data;
  24. throw new Error(`Network request error. status : ${response.status}`);
  25. };
  26. export default { fetch: api };