UnisKB/ui/src/request/index.ts

232 lines
6.0 KiB
TypeScript
Raw Normal View History

2023-09-15 09:40:35 +00:00
import axios, { type AxiosRequestConfig } from 'axios'
2023-10-13 08:11:54 +00:00
import { MsgError } from '@/utils/message'
2023-09-15 09:40:35 +00:00
import type { NProgress } from 'nprogress'
import type { Ref } from 'vue'
import type { Result } from '@/request/Result'
2023-10-19 10:18:45 +00:00
import useStore from '@/stores'
2023-09-15 09:40:35 +00:00
import router from '@/router'
import { ref, type WritableComputedRef } from 'vue'
const axiosConfig = {
baseURL: '/api',
withCredentials: false,
timeout: 60000,
headers: {}
}
const instance = axios.create(axiosConfig)
2023-11-22 03:05:06 +00:00
/* 设置请求拦截器 */
2023-09-15 09:40:35 +00:00
instance.interceptors.request.use(
(config: AxiosRequestConfig) => {
if (config.headers === undefined) {
config.headers = {}
}
2023-10-19 10:18:45 +00:00
const { user } = useStore()
const token = user.getToken()
2023-09-15 09:40:35 +00:00
if (token) {
2023-10-19 10:18:45 +00:00
config.headers['AUTHORIZATION'] = `${token}`
2023-09-15 09:40:35 +00:00
}
return config
},
(err: any) => {
return Promise.reject(err)
}
)
//设置响应拦截器
instance.interceptors.response.use(
(response: any) => {
if (response.data) {
2023-11-30 06:10:39 +00:00
if (response.data.code !== 200 && !(response.data instanceof Blob)) {
2023-10-13 08:11:54 +00:00
MsgError(response.data.message)
2023-11-30 06:10:39 +00:00
return Promise.reject(response.data)
2023-09-15 09:40:35 +00:00
}
}
return response
},
(err: any) => {
if (err.code === 'ECONNABORTED') {
2023-10-13 08:11:54 +00:00
MsgError(err.message)
2023-09-15 09:40:35 +00:00
console.error(err)
}
if (err.response?.status === 401) {
router.push({ name: 'login' })
}
2023-12-01 10:21:49 +00:00
if (err.response?.status === 403 && !err.response.config.url.includes('chat/open')) {
2023-10-13 08:11:54 +00:00
MsgError(
2023-09-15 09:40:35 +00:00
err.response.data && err.response.data.message ? err.response.data.message : '没有权限访问'
)
}
return Promise.reject(err)
}
)
export const request = instance
/* 简化请求方法统一处理返回结果并增加loading处理这里以{success,data,message}格式的返回值为例,具体项目根据实际需求修改 */
const promise: (
request: Promise<any>,
loading?: NProgress | Ref<boolean> | WritableComputedRef<boolean>
) => Promise<Result<any>> = (request, loading = ref(false)) => {
return new Promise((resolve, reject) => {
if ((loading as NProgress).start) {
;(loading as NProgress).start()
} else {
;(loading as Ref).value = true
}
request
.then((response) => {
// blob类型的返回状态是response.status
2023-11-27 09:06:39 +00:00
if (response.status === 200) {
resolve(response?.data || response)
2023-09-15 09:40:35 +00:00
} else {
2023-11-27 09:06:39 +00:00
reject(response?.data || response)
2023-09-15 09:40:35 +00:00
}
})
.catch((error) => {
reject(error)
})
.finally(() => {
if ((loading as NProgress).start) {
;(loading as NProgress).done()
} else {
;(loading as Ref).value = false
}
})
})
}
/**
* get
* @param url url
* @param params
* @param loading loading
* @returns promise
*/
export const get: (
url: string,
params?: unknown,
loading?: NProgress | Ref<boolean>
) => Promise<Result<any>> = (url: string, params: unknown, loading?: NProgress | Ref<boolean>) => {
return promise(request({ url: url, method: 'get', params }), loading)
}
/**
* faso post
* @param url url
* @param params
* @param data
* @param loading loading
* @returns promise
*/
export const post: (
url: string,
data?: unknown,
2023-10-20 03:26:14 +00:00
params?: unknown,
2023-09-15 09:40:35 +00:00
loading?: NProgress | Ref<boolean>
2023-10-20 03:26:14 +00:00
) => Promise<Result<any> | any> = (url, data, params, loading) => {
2023-09-15 09:40:35 +00:00
return promise(request({ url: url, method: 'post', data, params }), loading)
}
/**|
* put
* @param url
* @param params params
* @param data
* @param loading
* @returns
*/
export const put: (
url: string,
data?: unknown,
2023-12-08 08:55:29 +00:00
params?: unknown,
2023-09-15 09:40:35 +00:00
loading?: NProgress | Ref<boolean>
2023-11-10 03:36:04 +00:00
) => Promise<Result<any>> = (url, data, params, loading) => {
return promise(request({ url: url, method: 'put', data, params }), loading)
2023-09-15 09:40:35 +00:00
}
/**
*
* @param url url
* @param params params
* @param loading
* @returns
*/
export const del: (
url: string,
params?: unknown,
data?: unknown,
loading?: NProgress | Ref<boolean>
) => Promise<Result<any>> = (url, params, data, loading) => {
2023-10-20 10:48:16 +00:00
return promise(request({ url: url, method: 'delete', params, data }), loading)
2023-09-15 09:40:35 +00:00
}
2023-11-27 10:08:58 +00:00
/**
*
* @param url url
* @param data body
* @returns
*/
export const postStream: (url: string, data?: unknown) => Promise<Result<any> | any> = (
url,
data
) => {
const { user } = useStore()
const token = user.getToken()
const headers: HeadersInit = { 'Content-Type': 'application/json' }
if (token) {
headers['AUTHORIZATION'] = `${token}`
}
return fetch(url, {
method: 'POST',
body: data ? JSON.stringify(data) : undefined,
headers: headers
})
2023-11-27 09:06:39 +00:00
}
2023-09-15 09:40:35 +00:00
export const exportExcel: (
fileName: string,
url: string,
params: any,
loading?: NProgress | Ref<boolean>
) => void = (fileName: string, url: string, params: any, loading?: NProgress | Ref<boolean>) => {
promise(request({ url: url, method: 'get', params, responseType: 'blob' }), loading)
.then((res: any) => {
if (res) {
const blob = new Blob([res], {
type: 'application/vnd.ms-excel'
})
const link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = fileName
link.click()
//释放内存
window.URL.revokeObjectURL(link.href)
}
})
.catch((e) => {
console.log(e)
})
}
/**
* ws
* @param url websocket
* @returns websocket
*/
export const socket = (url: string) => {
let protocol = 'ws://'
if (window.location.protocol === 'https:') {
protocol = 'wss://'
}
let uri = protocol + window.location.host + url
if (!import.meta.env.DEV) {
uri = protocol + window.location.host + import.meta.env.VITE_BASE_PATH + url
}
return new WebSocket(uri)
}
export default instance