feat: 前后端统一接口类型

This commit is contained in:
ChenZhaoYu
2023-02-13 15:54:17 +08:00
parent dd522eb404
commit 847623e22a
12 changed files with 167 additions and 78 deletions

View File

@@ -0,0 +1,29 @@
import axios, { type AxiosResponse } from 'axios'
const service = axios.create({
baseURL: import.meta.env.VITE_GLOB_API_URL,
timeout: 10 * 1000,
})
service.interceptors.request.use(
(config) => {
return config
},
(error) => {
return Promise.reject(error.response)
},
)
service.interceptors.response.use(
(response: AxiosResponse): AxiosResponse => {
if (response.status === 200)
return response
throw new Error(response.status.toString())
},
(error) => {
return Promise.reject(error)
},
)
export default service

View File

@@ -0,0 +1,72 @@
import type { AxiosResponse } from 'axios'
import request from './axios'
export interface HttpOption {
url: string
data?: any
method?: string
headers?: any
beforeRequest?: () => void
afterRequest?: () => void
}
export interface ExtraOption {
notification?: boolean
}
export interface Response<T = any> {
data: T
message: string | null
status: string
}
function http<T = any>({ url, data, method, headers, beforeRequest, afterRequest }: HttpOption) {
const successHandler = (res: AxiosResponse<Response<T>>) => {
if (res.data.status === 'Success')
return res.data
return Promise.reject(res.data)
}
const failHandler = (error: Response<Error>) => {
afterRequest?.()
throw new Error(error?.message || 'Error')
}
beforeRequest?.()
method = method || 'GET'
const params = Object.assign(typeof data === 'function' ? data() : data ?? {}, {})
return method === 'GET'
? request.get(url, { params }).then(successHandler, failHandler)
: request.post(url, params, { headers }).then(successHandler, failHandler)
}
export function get<T = any>(
{ url, data, method = 'GET', beforeRequest, afterRequest }: HttpOption,
): Promise<Response<T>> {
return http<T>({
url,
method,
data,
beforeRequest,
afterRequest,
})
}
export function post<T = any>(
{ url, data, method = 'POST', headers, beforeRequest, afterRequest }: HttpOption,
): Promise<Response<T>> {
return http<T>({
url,
method,
data,
headers,
beforeRequest,
afterRequest,
})
}
export default post