import type { AxiosRequestConfig } from 'axios' import axios, { AxiosInstance } from 'axios' export class AxiosService { protected axios: AxiosInstance constructor( config?: AxiosRequestConfig ) { if (!config) config = {} this.axios = axios.create(config) } protected async apiRequest(config: AxiosRequestConfig, url: string, data?: any) { if (!config.headers) config.headers = {} config.headers['Content-Type'] = 'application/json' return this.axios({ ...config, url, data: data, }).then((res) => { return res.data }) } protected async apiRequestHeader(config: AxiosRequestConfig, url: string, headerToRetrieve?: string, data?: any,) { if (!config.headers) config.headers = {} config.headers['Content-Type'] = 'application/json' return this.axios({ ...config, url, data: data, }).then((res) => { if (headerToRetrieve) { return res.headers[headerToRetrieve] ?? res.headers[headerToRetrieve.toLowerCase()] } return res.headers }) } public get(url: string, config?: AxiosRequestConfig): Promise { return this.apiRequest({ ...config, method: 'get' }, url) } public deleteRequest( url: string, config?: AxiosRequestConfig ): Promise { return this.apiRequest({ ...config, method: 'delete' }, url) } public post( url: string, data?: any, config?: AxiosRequestConfig ): Promise { return this.apiRequest({ ...config, method: 'post' }, url, data) } public put( url: string, data: any, config?: AxiosRequestConfig ): Promise { return this.apiRequest({ ...config, method: 'put' }, url, data) } public patch( url: string, data: any, config?: AxiosRequestConfig ): Promise { return this.apiRequest({ ...config, method: 'patch' }, url, data) } public head( url: string, config?: AxiosRequestConfig, headerToRetrieve?: string, data?: any ): Promise { return this.apiRequestHeader({ ...config, method: 'head' }, url, headerToRetrieve, data) } }