api.ts 764 B

1234567891011121314151617181920212223242526272829303132
  1. import axios, { Method } from 'axios';
  2. export const BASE_URL = `http://${process.env.INTERNAL_IP}:3001`;
  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 response = await axios.request<T & { error?: string }>({
  12. method,
  13. params,
  14. data,
  15. url: `${BASE_URL}${endpoint}`,
  16. withCredentials: true,
  17. });
  18. if (response.data.error) {
  19. throw new Error(response.data.error);
  20. }
  21. if (response.data) return response.data;
  22. throw new Error(`Network request error. status : ${response.status}`);
  23. };
  24. export default { fetch: api };