import axios , { AxiosResponse } from 'axios' ; export interface IRequestConfig { query ? : any ; method ? : 'GET' | 'POST' | 'PATCH' | 'DELETE' | 'PUT' | 'DELETE' ; withCredentials ? : boolean ; } ; const request = async ( endpoint , data , config ) => { let requestUrl = endpoint ; if ( config . query ) { Object . keys ( config . query ) . forEach ( ( key , index ) => { const value = config . query [ key ] ; if ( value === undefined ) { return ; } requestUrl += ( index === 0 ? '?' : '&' ) + `${ key }=${ value }` ; } ) ; } delete config . query ; const finalConfig = { ... config , withCredentials : true , } ; let response ; try { if ( config . method === 'GET' ) { response = await axios . get ( requestUrl , finalConfig ) ; } else if ( config . method === 'POST' ) { response = await axios . post ( requestUrl , data , finalConfig ) ; } else if ( config . method === 'DELETE' ) { response = await axios . delete ( requestUrl , finalConfig ) ; } return response . data ; } catch ( e ) { if ( typeof window !== 'undefined' && e . response && e . response . status === 401 ) { window . location . href = '/login' ; } else { throw e ; } } } ; export const get = ( endpoint , query ? , config = { } ) => { return request ( endpoint , null , { ... config , query , method : 'GET' } ) ; } ; export const post = ( endpoint , data ? , config = { } ) => { return request ( endpoint , data , { ... config , method : 'POST' } ) ; } ; export const upload = ( endpoint , payload , config = { } ) => { const formData = new FormData ( ) ; Object . keys ( payload ) . forEach ( key => formData . append ( key , payload [ key ] ) ) ; return post ( endpoint , formData , config ) ; } ; export const deleteRequest = ( endpoint , data ? , config = { } ) => { return request ( endpoint , data , { ... config , method : 'DELETE' } ) ; } ;