Skip to content

Instantly share code, notes, and snippets.

@tiennguyendang
Last active April 10, 2023 07:13
Show Gist options
  • Save tiennguyendang/f0a25e350479b8fdfac296e36fcbb89d to your computer and use it in GitHub Desktop.
Save tiennguyendang/f0a25e350479b8fdfac296e36fcbb89d to your computer and use it in GitHub Desktop.
Create an http client with axios and Typescript
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'
const headers: Readonly<Record<string, string | boolean>> = {
Accept: 'application/json',
'Content-Type': 'application/json; charset=utf-8',
'X-Requested-With': 'XMLHttpRequest'
}
class Http {
private instance: AxiosInstance | null = null
private get http(): AxiosInstance {
return this.instance != null ? this.instance : this.initHttp()
}
initHttp() {
const http = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_BASEURL,
timeout: 10000,
headers
})
http.interceptors.response.use(
response => response.data.result,
error => {
let resolvedError: Record<string, unknown> | string
if (error.response) {
/*
* The request was made and the server responded with a
* status code that falls out of the range of 2xx
*/
resolvedError =
error.response.data.errors?.errors ??
error.response.data.errors?.message
} else if (error.request) {
/*
* The request was made but no response was received, `error.request`
* is an instance of XMLHttpRequest in the browser and an instance
* of http.ClientRequest in Node.js
*/
resolvedError = 'Server not Responding'
} else {
// Something happened in setting up the request and triggered an Error
resolvedError = error.message
}
return Promise.reject(resolvedError)
}
)
this.instance = http
return http
}
request<T, R = T>(config: AxiosRequestConfig): Promise<R> {
return this.http.request(config)
}
get<T, R = T>(url: string, config?: AxiosRequestConfig): Promise<R> {
return this.http.get<T, R>(url, config)
}
post<T, R = T>(
url: string,
data?: T,
config?: AxiosRequestConfig
): Promise<R> {
return this.http.post<T, R>(url, data, config)
}
put<T, R = T>(
url: string,
data?: T,
config?: AxiosRequestConfig
): Promise<R> {
return this.http.put<T, R>(url, data, config)
}
delete<T, R = T>(url: string, config?: AxiosRequestConfig): Promise<R> {
return this.http.delete<T, R>(url, config)
}
}
export const http = new Http()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment