request.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. import { logoutSuccess } from "@/store/user";
  2. import ToastUtil from "@/utils/toast_utils";
  3. import Taro from "@tarojs/taro";
  4. import { useDispatch } from "react-redux";
  5. import dayjs from 'dayjs'
  6. import { APP_VERSION, WX_VERSION } from "./api";
  7. import { getTimezone, getTimezoneId, getTimezoneName } from "@/utils/tools";
  8. import showAlert from "@/components/basic/Alert";
  9. const utc = require('dayjs/plugin/utc')
  10. const timezone = require('dayjs/plugin/timezone')
  11. dayjs.extend(utc)
  12. dayjs.extend(timezone)
  13. interface RequestParam {
  14. url: string;
  15. method: 'POST' | 'GET' | 'DELETE' | 'PUT';
  16. data?: Record<string, any>;
  17. showAlert?: boolean;
  18. }
  19. interface Resp {
  20. statusCode?: number;
  21. header?: any;
  22. data?: any;
  23. errMsg?: string;
  24. };
  25. async function getStorage(key: string) {
  26. try {
  27. const res = await Taro.getStorage({ key });
  28. return res.data;
  29. } catch {
  30. return '';
  31. }
  32. }
  33. //X-Language:语言,X-Device-Id:设备唯一码,X-Platform:小程序/android/ios,X-Location:地区,X-Device:登录设备
  34. // header['X-Language'] = ''
  35. // header['X-Device-Id'] = ''
  36. // header['X-Platform'] = ''
  37. // header['X-Location'] = ''
  38. // header['X-Device'] = ''
  39. // header['X-Time-Zone-Id'] = Intl.DateTimeFormat().resolvedOptions().timeZone
  40. // header['Authorization'] = 'Bearer ' + wx.getStorageSync('token');
  41. // header['Authorization'] = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhY2NvdW50Iiwic3ViIjoiMmQ5OWNlYzI0ZDFlMzE0Y2U1MjhlODM4MWMzYzk0MzgiLCJpc3MiOiJDT0RFUEFBUy5DT00iLCJuaWNrbmFtZSI6IueOi-a4nSIsInR5cCI6IkJlYXJlciIsInNlc3Npb25fc3RhdGUiOiIyN2RjNmU4ZDdjMWU1MTVmNDQwNzVjZTFlODk2ZmUzNCIsImV4cCI6MTcxNjY0Mzk5MSwiaWF0IjoxNjg1MDIxNTkxfQ.fmFj0OVNRzjLkdebSyGJyk8EScPJFpDiz0L25W35zoA'
  42. export async function request<T>(param: RequestParam): Promise<T> {
  43. const kTimeout = 8000;
  44. const kRetryCount = 2;
  45. let retryCount = 0;
  46. function performRequest(resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) {
  47. // if (process.env.TARO_ENV == 'rn' && Taro.getSystemInfoSync().platform != 'ios') {
  48. // return;
  49. // }
  50. const { url, method, data } = param;
  51. console.log(url)
  52. var requestTask: any = null;
  53. let header: any = {};
  54. const token = global.token ? global.token : ''; //await getStorage('token')
  55. var timeZoneFormatted = getTimezone()
  56. var timeZoneName = getTimezoneName()
  57. // var timeZoneLocation = Intl.DateTimeFormat().resolvedOptions().timeZone
  58. header['content-type'] = 'application/json'
  59. header['X-Timezone'] = encodeURIComponent(JSON.stringify({
  60. id:getTimezoneId(),
  61. name:timeZoneName?timeZoneName:'',
  62. gmt:timeZoneFormatted
  63. }))
  64. header['X-Platform'] = Taro.getSystemInfoSync().platform == 'ios' ? 'IOS' : 'ANDROID'; //IOS ANDROID
  65. header['X-Lang'] = process.env.TARO_ENV == 'rn' ? 'en' : 'zh' //zh en
  66. header['X-Client-Type'] = process.env.TARO_ENV == 'rn' ? 'APP' : 'WX_APP' //WX_APP APP
  67. header['X-Client-Version'] = process.env.TARO_ENV == 'rn' ? APP_VERSION : WX_VERSION
  68. if (token.length > 0) {
  69. header['Authorization'] = `Bearer ${token}`;
  70. }
  71. const timer = setTimeout(() => {
  72. requestTask && requestTask.abort();
  73. console.log('timeout');
  74. if (retryCount < kRetryCount) {
  75. // Retry the request
  76. console.log(`Retrying request (${retryCount + 1}/2)...`);
  77. retryCount++;
  78. performRequest(resolve, reject);
  79. return;
  80. }
  81. if (global.language == 'en') {
  82. ToastUtil.getInstance().showToast(method == 'GET' ?
  83. 'Network connection failed. Please check your network.' :
  84. 'Posting failed. Please check your network.');
  85. }
  86. else {
  87. ToastUtil.getInstance().showToast(method == 'GET' ? '网络连接失败,请检查网络' : '操作失败,请检查网络');
  88. }
  89. reject('timeout');
  90. }, kTimeout);
  91. requestTask = Taro.request({
  92. url: url,
  93. method: method,
  94. header: header,
  95. timeout: kTimeout,
  96. data: data || {},
  97. success: (response: Resp | { [key: string]: any }) => {
  98. clearTimeout(timer);
  99. const { statusCode, data } = response;
  100. if (statusCode != 200) {
  101. console.log(response)
  102. }
  103. if (statusCode >= 200 && statusCode < 300) {
  104. //正常数据返回
  105. var resp = {} as T;
  106. if (response.data) {
  107. resp = response.data as T;
  108. }
  109. resolve(resp);
  110. } else if (statusCode == 401) {
  111. // global.postBtnUpdateStatus('idle')
  112. //未登录或挤下线处理
  113. if (process.env.TARO_ENV == 'weapp') {
  114. Taro.stopPullDownRefresh()
  115. }
  116. else if (process.env.TARO_ENV == 'rn') {
  117. if (url.indexOf('login/password') != -1) {
  118. reject(data);
  119. return;
  120. }
  121. }
  122. if (global.dispatch) {
  123. global.dispatch(logoutSuccess());
  124. }
  125. } else if (statusCode == 500 && response.data.error_code == 'WX_STEP_PARSE_FAIL') {
  126. //单独对计步第一次请求失败处理
  127. resolve(response.data);
  128. } else {
  129. //通用错误处理
  130. Taro.showToast({
  131. icon: 'none',
  132. title: data.error_message,
  133. });
  134. reject(data);
  135. }
  136. },
  137. fail: err => {
  138. if ((err as any).statusCode >= 200 && (err as any).statusCode < 300) {
  139. clearTimeout(timer);
  140. resolve()
  141. return;
  142. }
  143. // global.postBtnUpdateStatus('idle')
  144. // console.log('oppsu');
  145. // clearTimeout(timer);
  146. // reject(err);
  147. },
  148. });
  149. }
  150. return new Promise<T>((resolve, reject) => {
  151. performRequest(resolve, reject);
  152. });
  153. }