通用代码
通用函数
pnpm安装如下库以使用通用函数
json
{
"dependencies": {
"axios": "^1.3.3",
"crypto-js": "^3.1.9-1",
"qs": "^6.11.0",
"tus-js-client": "^4.2.3"
}
}
如下是用axios统一封装好的请求库。接下来的示例都会使用这些函数/变量。所有的请求都使用request函数。
ts
//@ts-ignore
import * as CryptoJS from 'crypto-js'
import axios, { AxiosInstance } from 'axios'
import qs from 'qs'
import * as tus from 'tus-js-client'
/**
* 常量定义,需自己配置
*/
const CONSTANTS = {
API_URL: 'http://10.16.30.161:8555/api/', //接口地址(需要根据实际情况修改)
PWD_ENC_KEY: 'szzktxtuxinearth',
OAUTH2_PASSWORD_CLIENT: 'tuxinearth:tuxinearth',
TOKEN: '' //token
}
/**
* 创建并配置一个 Axios 实例对象
*/
const request: AxiosInstance = axios.create({
baseURL: CONSTANTS.API_URL,
timeout: 150000, // 全局超时时间
paramsSerializer: {
serialize: (params: any) => {
return qs.stringify(params, { arrayFormat: 'repeat' })
}
}
})
/**
* Axios请求拦截器,对请求进行处理
* 1. 序列化get请求参数
* 2. 统一增加Authorization和TENANT-ID请求头
* 3. 自动适配单体、微服务架构不同的URL
* @param config AxiosRequestConfig对象,包含请求配置信息
*/
request.interceptors.request.use(
async (config: any) => {
let token = CONSTANTS.TOKEN
// 统一增加Authorization请求头, skipToken 跳过增加token
if (token && !config.headers?.skipToken) {
config.headers![CommonHeaderEnum.AUTHORIZATION] = `Bearer ${token}`
}
// 统一增加TENANT-ID请求头
const tenantId = '1'
if (tenantId) {
config.headers![CommonHeaderEnum.TENANT_ID] = tenantId
}
// 请求报文加密
if (config.headers![CommonHeaderEnum.ENC_FLAG]) {
const enc = encryption(JSON.stringify(config.data), CONSTANTS.PWD_ENC_KEY)
config.data = {
encryption: enc
}
}
// 处理完毕,返回config对象
return config
},
(error) => {
// 对请求错误进行处理
return Promise.reject(error)
}
)
/**
* 响应拦截器处理函数
* @param response 响应结果
* @returns 如果响应成功,则返回响应的data属性;否则,抛出错误或者执行其他操作
*/
const handleResponse = (response: any) => {
/**返回原始的响应 */
if ((response.config as any).returnOriginResponse) {
return response
}
// 针对密文返回解密
if (response.data.encryption) {
const originData = JSON.parse(
decryption(response.data.encryption, CONSTANTS.PWD_ENC_KEY)
)
response.data = originData
return response.data
}
return response.data
}
/**
* 添加 Axios 的响应拦截器,用于全局响应结果处理
*/
request.interceptors.response.use(handleResponse, (error) => {
const status = Number(error.response.status) || 200
if (status === 423) {
return Promise.reject({ msg: '"演示环境,仅供预览"' })
}
if (status === 424) {
console.log('令牌状态已过期')
} else if (status === 555) {
console.log('许可已过期')
} else if (status === 401) {
console.log(error?.response?.data?.msg ?? '令牌状态已过期')
}
return Promise.reject(error.response.data)
})
// 常用header
export enum CommonHeaderEnum {
'TENANT_ID' = 'TENANT-ID',
'ENC_FLAG' = 'Enc-Flag',
'AUTHORIZATION' = 'Authorization'
}
/**解密 */
function decryption(src: string, keyWord: string) {
const key = CryptoJS.enc.Utf8.parse(keyWord)
// 解密逻辑
var decryptd = CryptoJS.AES.decrypt(src, key, {
iv: key,
mode: CryptoJS.mode.CFB,
padding: CryptoJS.pad.NoPadding
})
return decryptd.toString(CryptoJS.enc.Utf8)
}
/**加密 */
function encryption(src: string, keyWord: string) {
const key = CryptoJS.enc.Utf8.parse(keyWord)
// 加密
var encrypted = CryptoJS.AES.encrypt(src, key, {
iv: key,
mode: CryptoJS.mode.CFB,
padding: CryptoJS.pad.NoPadding
})
return encrypted.toString()
}
/**生成uuid */
function generateUUID() {
if (typeof crypto === 'object') {
if (typeof crypto.randomUUID === 'function') {
return crypto.randomUUID()
}
if (
typeof crypto.getRandomValues === 'function' &&
typeof Uint8Array === 'function'
) {
const callback = (c: any) => {
const num = Number(c)
return (
num ^
(crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (num / 4)))
).toString(16)
}
return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, callback)
}
}
let timestamp = new Date().getTime()
let performanceNow =
(typeof performance !== 'undefined' &&
performance.now &&
performance.now() * 1000) ||
0
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
let random = Math.random() * 16
if (timestamp > 0) {
random = (timestamp + random) % 16 | 0
timestamp = Math.floor(timestamp / 16)
} else {
random = (performanceNow + random) % 16 | 0
performanceNow = Math.floor(performanceNow / 16)
}
return (c === 'x' ? random : (random & 0x3) | 0x8).toString(16)
})
}
字典
获取字典列表
ts
/**获取字典列表
* @param query 查询条件
* @param query.name 字典名称(description)/字典项(dictType)
*/
function fetchItemList(query: { name?: string }) {
return request({
url: '/admin/dict/list',
method: 'get',
params: query
})
}
通过 dictType 获取系统字典值
ts
/**
* 获取dict
* @param type 字典类型
*/
export const getDicts = (type: String) => {
return request({
url: `/admin/dict/type/${type}`,
method: 'get'
})
}