107 lines
3.2 KiB
JavaScript
Raw Normal View History

2024-12-19 17:14:37 +08:00
import { getStorage, removeStorage } from '../export.js'
import starCloudInstance from '../star-cloud'
import { Result } from '../constant'
2024-12-19 16:01:45 +08:00
/*
* config
* baseUrl: 请求域名
* url: 请求路径
* method: 请求方法
* header: 请求头
* token: 请求token
* data: 请求参数
* */
const request = config => {
let timer
let res = null // 在外部定义res避免finally块报错
return new Promise(async resolve => {
2024-12-19 17:34:15 +08:00
const baseConfig = starCloudInstance.getConfig()
2024-12-19 16:01:45 +08:00
const token = config?.token ? config.token : getStorage('starCloudToken')
// 请求地址
const URL = config.baseUrl ? config.baseUrl + config.url : baseConfig.baseUrl + config.url
// 默认请求头
const headerDefault = {
version: baseConfig.version + '+' + baseConfig.buildNumber
}
const header = {
...headerDefault,
...config.header
}
const method = config.method || 'POST'
const data = {
...config.data,
accessToken: token,
2024-12-19 17:34:15 +08:00
clientId: starCloudInstance.clientId
2024-12-19 16:01:45 +08:00
}
const timestamp = new Date().getTime()
// 超时处理
timer = setTimeout(() => {
resolve(new Result(Result.Fail.code, {}, '网络访问失败,请检查网络是否正常'))
}, 3200)
try {
const response = await fetch(URL, {
method,
headers: {
...header,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
res = await response.json() // 在这里将res赋值
if (timer) {
clearTimeout(timer)
}
if (response.ok) {
const { errcode, errmsg, data } = res
if (errcode === 10003) {
removeStorage('starCloudToken')
removeStorage('starCloudUser')
2024-12-19 17:34:15 +08:00
const { code } = await starCloudInstance.login({
username: starCloudInstance.starCloudAccountInfo.username,
password: starCloudInstance.starCloudAccountInfo.password,
uid: starCloudInstance.starCloudAccountInfo.uid
2024-12-19 16:01:45 +08:00
})
if (code === Result.Success.code) {
resolve(await request(config))
}
} else {
resolve({
code: errcode,
data,
message: errmsg
})
}
} else {
resolve(new Result(Result.Fail.code, {}, '网络访问失败,请检查网络是否正常'))
}
} catch (error) {
console.log('网络访问失败', error)
if (timer) {
clearTimeout(timer)
}
resolve(new Result(Result.Fail.code, {}, '网络访问失败,请检查网络是否正常'))
} finally {
// 访问res时确保它已定义
console.log(URL.substring(baseConfig.baseUrl.length + 1), {
env: baseConfig.name,
url: URL.substring(baseConfig.baseUrl.length + 1),
req: config?.data || {},
code: res?.errcode || null, // 如果res未定义fallback为null
res: res?.data || null, // 如果res未定义fallback为null
token: header?.authorization || '',
message: res?.errmsg || '', // 如果res未定义fallback为空字符串
duration: new Date().getTime() - timestamp
})
}
})
}
export default request