am-freescan/am-web/src/cmvr/request.ts

40 lines
1.8 KiB
TypeScript
Raw Normal View History

2026-10-22 16:18:37 +08:00
import axios from 'axios'
import { ElLoading, ElMessage } from 'element-plus'
import { saveAs } from 'file-saver'
import { getAccessToken, getTenantId, getVisitTenantId } from '@/utils/auth'
/** CMVR keeps its AjaxResult/table contracts while sharing FreeScan authentication. */
export const cmvrApiBase = `${import.meta.env.VITE_BASE_URL}/admin-api/cmvr`
export const isRelogin = { show: false }
const request = axios.create({ baseURL: cmvrApiBase, timeout: 60000 })
request.interceptors.request.use((config) => {
const token = getAccessToken()
if (token) config.headers.Authorization = `Bearer ${token}`
config.headers['tenant-id'] = getTenantId() ?? 1
const visitTenantId = getVisitTenantId()
if (visitTenantId) config.headers['visit-tenant-id'] = visitTenantId
return config
})
request.interceptors.response.use((response) => {
if (response.config.responseType === 'blob' || response.config.responseType === 'arraybuffer') return response.data
const result = response.data
if (result?.code != null && result.code !== 200 && result.code !== 0) {
const error = new Error(result.msg || result.message || '请求失败')
ElMessage.error(error.message)
return Promise.reject(error)
}
return result
}, (error) => {
ElMessage.error(error.response?.data?.msg || error.message || 'CMVR 服务连接失败')
return Promise.reject(error)
})
export async function download(url: string, params: Record<string, any>, filename: string, config = {}) {
const loading = ElLoading.service({ text: '正在下载数据,请稍候' })
try {
const data: any = await request.post(url, new URLSearchParams(params), { responseType: 'blob', ...config })
if (data.type?.includes('json')) throw new Error((JSON.parse(await data.text())).msg || '下载失败')
saveAs(data, filename)
} finally { loading.close() }
}
export default request