2024-12-19 16:01:45 +08:00

108 lines
3.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { getStorage, removeStorage } from '@/starCloud/uniapp/storage'
import starCloudInstance from '@/starCloud/star-cloud'
import { Result } from '@/constants/result'
/*
* config
* baseUrl: 请求域名
* url: 请求路径
* method: 请求方法
* header: 请求头
* token: 请求token
* data: 请求参数
* */
const request = config => {
const starCloud = starCloudInstance
let timer
let res = null // 在外部定义res避免finally块报错
return new Promise(async resolve => {
const baseConfig = starCloud.getConfig()
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,
clientId: starCloud.clientId
}
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')
const { code } = await starCloud.login({
username: starCloud.starCloudAccountInfo.username,
password: starCloud.starCloudAccountInfo.password,
uid: starCloud.starCloudAccountInfo.uid
})
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