import { CustomError } from './CustomError' ; import axios , { AxiosResponse , AxiosError } from 'axios' ; import { RequestHeader } from './RequestHeader' ; import { goTry } from 'go-try' ; function handleResponse < ResponseData > ( response ) { return response . data ; } function handleError ( err ) { const { response } = err ; const status = response ?. status || 500 ; const message = response ?. data . message || response ?. statusText ; throw new CustomError ( status , message ) ; } export interface FetcherPostConfig { onUploadProgress : ( percentCompleted : number ) => void ; } class Fetcher { setCSRFToken = ( csrfToken ) => { axios . defaults . headers . common [ RequestHeader . CSRF_TOKEN ] = csrfToken ; } ; get = async < ResponseData = any > ( url ) => { const result = await goTry < AxiosResponse < ResponseData > , AxiosError > ( ( ) => axios . get < ResponseData > ( url ) ) ; if ( result . error ) { throw handleError ( result . error ) ; } return handleResponse ( result . data ) ; } ; post = async < ResponseData = any , PostData = any > ( url , data ? , config ? ) : Promise < ResponseData > => { const result = await goTry < AxiosResponse < ResponseData > , AxiosError > ( ( ) => axios . post < ResponseData > ( url , data , { onUploadProgress : config ?. onUploadProgress ? ( progressEvent ) => { const percentCompleted = Math . round ( ( progressEvent . loaded * 100 ) / progressEvent . total ) ; config . onUploadProgress ( percentCompleted ) ; } : undefined , } ) ) ; if ( result . error ) { throw handleError ( result . error ) ; } return handleResponse ( result . data ) ; } ; } export const fetcher = new Fetcher ( ) ;