| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228 |
- 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 } from "./api";
- import { getTimezone, getTimezoneId, getTimezoneName } from "@/utils/tools";
- import showAlert from "@/components/basic/Alert";
- const utc = require('dayjs/plugin/utc')
- const timezone = require('dayjs/plugin/timezone')
- dayjs.extend(utc)
- dayjs.extend(timezone)
- 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) {
- // if (process.env.TARO_ENV == 'rn' && Taro.getSystemInfoSync().platform != 'ios') {
- // return;
- // }
- 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-Timezone'] = encodeURIComponent(JSON.stringify({
- id: getTimezoneId(),
- name: timeZoneName ? timeZoneName : '',
- gmt: timeZoneFormatted
- }))
- header['X-Platform'] = Taro.getSystemInfoSync().platform == 'ios' ? 'IOS' : 'ANDROID'; //IOS ANDROID
- header['X-Lang'] = process.env.TARO_ENV == 'rn' ? 'en' : 'zh' //zh en
- header['X-Client-Type'] = process.env.TARO_ENV == 'rn' ? 'APP' : 'WX_APP' //WX_APP APP
- header['X-Client-Version'] = process.env.TARO_ENV == 'rn' ? 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.eyJhdWQiOiJhY2NvdW50Iiwic3ViIjoiZTQ3M2RlZDI4YzgwNzY3ZDZiOTBkYzAzMDg5YzRhYzEiLCJpc3MiOiJmYXN0Iiwibmlja25hbWUiOiLmtYvor5UiLCJ0eXAiOiJCZWFyZXIiLCJzZXNzaW9uX3N0YXRlIjoiNDE1NTZkODNiM2QyODRmYzNhODY1NmI3YzdhOTBjODQiLCJleHAiOjIwMzM3ODU4MTcsImlhdCI6MTcxODI1MzAxN30.JBbFZhmckizGqblsFFB3ee3u_CivwTR8w-0VoUcph2w';
- // 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);
- 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 (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<T>((resolve, reject) => {
- performRequest(resolve, reject);
- });
- }
|