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