| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142 |
- import { logoutSuccess } from "@/store/user";
- import ToastUtil from "@/utils/toast_utils";
- import Taro from "@tarojs/taro";
- import { useDispatch } from "react-redux";
- interface RequestParam {
- url: string;
- method: 'POST' | 'GET' | 'DELETE' | 'PUT';
- data?: Record<string, any>;
- 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<T>(param: RequestParam): Promise<T> {
- const kTimeout = 8000;
- const kRetryCount = 2;
- let retryCount = 0;
- function performRequest(resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) {
- const { url, method, data } = param;
- var requestTask: any = null;
- let header: any = {};
- const token = global.token ? global.token : ''; //await getStorage('token')
- var split = new Date().toString().split(' ');
- var timeZoneFormatted = split[split.length - 2];
- header['content-type'] = 'application/json'
- header['X-Time-Zone'] = timeZoneFormatted; //new Date().getTimezoneOffset() / 60
- header['X-Platform'] = 'IOS'; //IOS ANDROID
- header['X-Lang'] = 'zh' //zh en
- header['X-Client-Type'] = 'WX_APP' //WX_APP APP
- header['X-Client_Version'] = '1.0'
- if (token.length > 0) {
- header['Authorization'] = `Bearer ${token}`;
- }
- 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;
- }
- ToastUtil.getInstance().showToast(method == 'GET' ? '网络连接失败,请检查网络' : '操作失败,请检查网络');
- reject('timeout');
- }, kTimeout);
- 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()
- }
- global.dispatch(logoutSuccess());
- } else if (statusCode == 500 && response.data.error_code == 'WX_STEP_PARSE_FAIL') {
- //单独对计步第一次请求失败处理
- resolve(response.data);
- } else {
- //通用错误处理
- Taro.showToast({
- icon: 'none',
- title: data.error_message,
- });
- reject(data);
- }
- },
- fail: err => {
- console.log('oooooooddd', err)
- // global.postBtnUpdateStatus('idle')
- // console.log('oppsu');
- // clearTimeout(timer);
- // reject(err);
- },
- });
- }
- return new Promise<T>((resolve, reject) => {
- performRequest(resolve, reject);
- });
- }
|