github.com/filecoin-project/bacalhau@v0.3.23-0.20230228154132-45c989550ace/dashboard/frontend/src/hooks/useApi.ts (about) 1 import axios, { AxiosRequestConfig } from 'axios' 2 import { useContext, useCallback } from 'react' 3 4 import { 5 SnackbarContext, 6 } from '../contexts/snackbar' 7 8 const API_MOUNT = "" 9 10 export interface IApiOptions { 11 snackbar?: boolean, 12 } 13 14 export const getTokenHeaders = (token: string) => { 15 return { 16 Authorization: `Bearer ${token}`, 17 } 18 } 19 20 export const extractErrorMessage = (error: any): string => { 21 if(error.response && error.response.data && (error.response.data.message || error.response.data.error)) { 22 return error.response.data.message || error.response.data.error 23 } 24 else { 25 return error.toString() 26 } 27 } 28 29 export const useApi = () => { 30 31 const snackbar = useContext(SnackbarContext) 32 33 const get = useCallback(async function<ResT = any>(url: string, axiosConfig?: AxiosRequestConfig, options?: IApiOptions): Promise<ResT | null> { 34 try { 35 const res = await axios.get<ResT>(`${API_MOUNT}${url}`, axiosConfig) 36 return res.data 37 } catch (e: any) { 38 console.error(e) 39 if(options?.snackbar !== false) snackbar.setSnackbar(extractErrorMessage(e), 'error') 40 return null 41 } 42 }, []) 43 44 const post = useCallback(async function<ReqT = any, ResT = any>(url: string, data: ReqT, axiosConfig?: AxiosRequestConfig, options?: IApiOptions): Promise<ResT | null> { 45 try { 46 const res = await axios.post<ResT>(`${API_MOUNT}${url}`, data, axiosConfig) 47 return res.data 48 } catch (e: any) { 49 console.error(e) 50 if(options?.snackbar !== false) snackbar.setSnackbar(extractErrorMessage(e), 'error') 51 return null 52 } 53 }, []) 54 55 const put = useCallback(async function<ReqT = any, ResT = any>(url: string, data: ReqT, axiosConfig?: AxiosRequestConfig, options?: IApiOptions): Promise<ResT | null> { 56 try { 57 const res = await axios.put<ResT>(`${API_MOUNT}${url}`, data, axiosConfig) 58 return res.data 59 } catch (e: any) { 60 console.error(e) 61 if(options?.snackbar !== false) snackbar.setSnackbar(extractErrorMessage(e), 'error') 62 return null 63 } 64 }, []) 65 66 const del = useCallback(async function<ResT = any>(url: string, axiosConfig?: AxiosRequestConfig, options?: IApiOptions): Promise<ResT | null> { 67 try { 68 const res = await axios.delete<ResT>(`${API_MOUNT}${url}`, axiosConfig) 69 return res.data 70 } catch (e: any) { 71 console.error(e) 72 if(options?.snackbar !== false) snackbar.setSnackbar(extractErrorMessage(e), 'error') 73 return null 74 } 75 }, []) 76 77 const setToken = useCallback(function(token: string) { 78 axios.defaults.headers.common = token ? getTokenHeaders(token) : {} 79 }, []) 80 81 return { 82 get, 83 post, 84 put, 85 delete: del, 86 setToken, 87 } 88 } 89 90 export default useApi