koel/resources/assets/js/services/httpService.ts

75 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-04-15 14:24:30 +00:00
import Axios, { AxiosInstance, Method } from 'axios'
import NProgress from 'nprogress'
import { eventBus } from '@/utils'
2022-04-24 08:50:45 +00:00
import { authService, localStorageService } from '@/services'
2022-04-15 14:24:30 +00:00
2022-04-24 08:50:45 +00:00
export const httpService = {
2022-04-15 14:24:30 +00:00
client: null as AxiosInstance | null,
setProgressBar: () => NProgress.start(),
hideProgressBar: () => NProgress.done(true),
2022-04-23 22:47:21 +00:00
request<T> (method: Method, url: string, data: Record<string, any> = {}, onUploadProgress?: any) {
return this.client!.request({
2022-04-15 14:24:30 +00:00
url,
data,
method,
onUploadProgress
}) as Promise<{ data: T }>
},
2022-04-23 22:47:21 +00:00
async get<T> (url: string) {
2022-04-15 14:24:30 +00:00
return (await this.request<T>('get', url)).data
},
2022-04-23 22:47:21 +00:00
async post<T> (url: string, data: Record<string, any>, onUploadProgress?: any) {
2022-04-15 14:24:30 +00:00
return (await this.request<T>('post', url, data, onUploadProgress)).data
},
2022-04-23 22:47:21 +00:00
async put<T> (url: string, data: Record<string, any>) {
2022-04-15 14:24:30 +00:00
return (await this.request<T>('put', url, data)).data
},
2022-04-23 22:47:21 +00:00
async delete<T> (url: string, data: Record<string, any> = {}) {
2022-04-15 14:24:30 +00:00
return (await this.request<T>('delete', url, data)).data
},
2022-04-23 22:49:26 +00:00
init () {
2022-04-15 14:24:30 +00:00
this.client = Axios.create({
baseURL: `${window.BASE_URL}api`
2022-04-15 14:24:30 +00:00
})
// Intercept the request to make sure the token is injected into the header.
this.client.interceptors.request.use(config => {
this.setProgressBar()
2022-04-24 08:50:45 +00:00
config.headers.Authorization = `Bearer ${authService.getToken()}`
2022-04-15 14:24:30 +00:00
return config
})
// Intercept the response and…
this.client.interceptors.response.use(response => {
this.hideProgressBar()
// …get the token from the header or response data if exists, and save it.
const token = response.headers.Authorization || response.data.token
2022-04-24 08:50:45 +00:00
token && authService.setToken(token)
2022-04-15 14:24:30 +00:00
return response
}, error => {
this.hideProgressBar()
// Also, if we receive a Bad Request / Unauthorized error
if (error.response.status === 400 || error.response.status === 401) {
// and we're not trying to log in
if (!(error.config.method === 'post' && /\/api\/me\/?$/.test(error.config.url))) {
// the token must have expired. Log out.
eventBus.emit('LOG_OUT')
}
}
return Promise.reject(error)
})
}
}