import { logoutSuccess } from "@/store/user"; import ToastUtil from "@/utils/toast_utils"; import Taro from "@tarojs/taro"; import { useDispatch } from "react-redux"; import dayjs from 'dayjs' import { APP_VERSION, WX_VERSION, ANDROID_VERSION } from "./api"; import { getTimezone, getTimezoneId, getTimezoneName, kIsAndroid } from "@/utils/tools"; import showAlert from "@/components/basic/Alert"; const utc = require('dayjs/plugin/utc') const timezone = require('dayjs/plugin/timezone') const PROJECT_NAME = 'TIME' //FAST dayjs.extend(utc) dayjs.extend(timezone) interface RequestParam { url: string; method: 'POST' | 'GET' | 'DELETE' | 'PUT'; data?: Record; showAlert?: boolean; } interface Resp { statusCode?: number; header?: any; data?: any; errMsg?: string; }; async function getStorage(key: string) { try { const res = await Taro.getStorage({ key }); return res.data; } catch { return ''; } } //X-Language:语言,X-Device-Id:设备唯一码,X-Platform:小程序/android/ios,X-Location:地区,X-Device:登录设备 // header['X-Language'] = '' // header['X-Device-Id'] = '' // header['X-Platform'] = '' // header['X-Location'] = '' // header['X-Device'] = '' // header['X-Time-Zone-Id'] = Intl.DateTimeFormat().resolvedOptions().timeZone // header['Authorization'] = 'Bearer ' + wx.getStorageSync('token'); // header['Authorization'] = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhY2NvdW50Iiwic3ViIjoiMmQ5OWNlYzI0ZDFlMzE0Y2U1MjhlODM4MWMzYzk0MzgiLCJpc3MiOiJDT0RFUEFBUy5DT00iLCJuaWNrbmFtZSI6IueOi-a4nSIsInR5cCI6IkJlYXJlciIsInNlc3Npb25fc3RhdGUiOiIyN2RjNmU4ZDdjMWU1MTVmNDQwNzVjZTFlODk2ZmUzNCIsImV4cCI6MTcxNjY0Mzk5MSwiaWF0IjoxNjg1MDIxNTkxfQ.fmFj0OVNRzjLkdebSyGJyk8EScPJFpDiz0L25W35zoA' export async function request(param: RequestParam): Promise { const kTimeout = 8000; const kRetryCount = 2; let retryCount = 0; function performRequest(resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) { const { url, method, data } = param; console.log(url) var requestTask: any = null; let header: any = {}; const token = global.token ? global.token : ''; //await getStorage('token') var timeZoneFormatted = getTimezone() var timeZoneName = getTimezoneName() // var timeZoneLocation = Intl.DateTimeFormat().resolvedOptions().timeZone header['content-type'] = 'application/json' header['X-Project'] = process.env.TARO_ENV == 'rn' && kIsAndroid?'TIME':'FAST' header['X-Timezone'] = encodeURIComponent(JSON.stringify({ id: getTimezoneId(), name: timeZoneName ? timeZoneName : '', gmt: timeZoneFormatted })) header['X-Platform'] = Taro.getDeviceInfo().platform == 'ios' ? 'IOS' : 'ANDROID'; //IOS ANDROID header['X-Lang'] = process.env.TARO_ENV == 'rn' ? global.language : 'zh' //zh en if (process.env.TARO_ENV == 'weapp'){ header['X-Lang'] = global.language??'zh' } header['X-Client-Type'] = process.env.TARO_ENV == 'rn' ? 'APP' : 'WX_APP' //WX_APP APP header['X-Client-Version'] = process.env.TARO_ENV == 'rn' ? kIsAndroid ? ANDROID_VERSION : APP_VERSION : WX_VERSION header['X-Day'] = dayjs().format('YYYYMMDD') header['X-Timestamp'] = new Date().getTime() if (token.length > 0) { header['Authorization'] = `Bearer ${token}`; // header['Authorization'] = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhY2NvdW50Iiwic3ViIjoiMTE0Nzg0NGE5NDIyODk1MmE5Zjc2OTdjYWJjYmU3Y2UiLCJpc3MiOiJmYXN0Iiwibmlja25hbWUiOiJGYXN0ZXIiLCJ0eXAiOiJCZWFyZXIiLCJzZXNzaW9uX3N0YXRlIjoiZWE5NTQ1Y2VkNThlNzgzNTA1MWRjZTY0ODEwMzQ4ZmQiLCJleHAiOjE3NDk3MDA3MTYsImlhdCI6MTcxODE2NDcxN30.yrh-xAJhmfG-CueyCsToW-X4Dx043DYhk5DiE0E4eNk'; // header['Authorization'] = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhY2NvdW50Iiwic3ViIjoiMjZkOGE1YTg0MDMyYmExN2Q4NDk3MTlkNTljNGY1NzgiLCJpc3MiOiJmYXN0Iiwibmlja25hbWUiOiJCSyIsInR5cCI6IkJlYXJlciIsInNlc3Npb25fc3RhdGUiOiI1ZDU2NTkzYmNjNWFmNzM0OWNlZTMwZjlkNGYzMWIyMCIsImV4cCI6MTc0ODE3MDg5NSwiaWF0IjoxNzE2NjM0ODk1fQ.uaRm2vSNCX8fkFS63Oe-WNWIDHG_cRM-nQ5EGyUMaBg'; } const timer = setTimeout(() => { requestTask && requestTask.abort(); console.log('timeout'); if (retryCount < kRetryCount) { // Retry the request console.log(`Retrying request (${retryCount + 1}/2)...`); retryCount++; performRequest(resolve, reject); return; } if (process.env.TARO_ENV == 'rn' && (param.data as any).showAlert) { showAlert({ title: 'error', content: global.language == 'en' ? 'Posting failed. Please check your network.' : '操作失败,请检查网络', showCancel: false }) } else { if (global.language == 'en') { ToastUtil.getInstance().showToast(method == 'GET' ? 'Network connection failed. Please check your network.' : 'Posting failed. Please check your network.'); } else { ToastUtil.getInstance().showToast(method == 'GET' ? '网络连接失败,请检查网络' : '操作失败,请检查网络'); } } reject('timeout'); }, kTimeout); // var requestData; // if (data && data.length>0){ // requestData = JSON.parse(JSON.stringify(data)); // requestData.remove('showAlert') // } requestTask = Taro.request({ url: url, method: method, header: header, timeout: kTimeout, data: data || {}, success: (response: Resp | { [key: string]: any }) => { clearTimeout(timer); const { statusCode, data } = response; if (statusCode != 200) { console.log(response) } if (statusCode >= 200 && statusCode < 300) { //正常数据返回 var resp = {} as T; if (response.data) { resp = response.data as T; } resolve(resp); } else if (statusCode == 401) { // global.postBtnUpdateStatus('idle') //未登录或挤下线处理 if (process.env.TARO_ENV == 'weapp') { Taro.stopPullDownRefresh() } else if (process.env.TARO_ENV == 'rn') { if (url.indexOf('login/password') != -1) { reject(data); return; } } if (global.dispatch) { global.dispatch(logoutSuccess()); } } else if (statusCode == 500 && response.data.error_code == 'WX_STEP_PARSE_FAIL') { //单独对计步第一次请求失败处理 resolve(response.data); } else { //通用错误处理 if (statusCode == 502) { if (process.env.TARO_ENV == 'rn' && (param.data as any).showAlert) { showAlert({ title: 'error', content: global.language == 'en' ? 'Server is busy now. Please try again later.' : '服务器正忙, 请您稍后再试。', showCancel: false }) } else { Taro.showToast({ icon: 'none', title: global.language == 'en' ? 'Server is busy now. Please try again later.' : '服务器正忙, 请您稍后再试。', }); } } else { if (response.data.error_code == 'BIZ_FAIL') { return; } if (process.env.TARO_ENV == 'rn' && (param.data as any).showAlert) { showAlert({ title: 'error', content: data.error_message, showCancel: false }) } else { Taro.showToast({ icon: 'none', title: data.error_message, }); } } reject(data); } }, fail: err => { if ((err as any).statusCode >= 200 && (err as any).statusCode < 300) { clearTimeout(timer); resolve() return; } // global.postBtnUpdateStatus('idle') // console.log('oppsu'); // clearTimeout(timer); // reject(err); }, }); } return new Promise((resolve, reject) => { performRequest(resolve, reject); }); }