request.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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, 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. const { url, method, data } = param;
  48. console.log(url)
  49. var requestTask: any = null;
  50. let header: any = {};
  51. const token = global.token ? global.token : ''; //await getStorage('token')
  52. var timeZoneFormatted = getTimezone()
  53. var timeZoneName = getTimezoneName()
  54. // var timeZoneLocation = Intl.DateTimeFormat().resolvedOptions().timeZone
  55. header['content-type'] = 'application/json'
  56. header['X-Time-Zone'] = timeZoneFormatted; //new Date().getTimezoneOffset() / 60
  57. // header['X-Time-Zone-Name'] = timeZoneName;
  58. if (Taro.getSystemInfoSync().platform == 'ios') {
  59. header['X-Time-Zone-Id'] = dayjs.tz.guess() ? dayjs.tz.guess() : '';
  60. }
  61. header['X-Platform'] = Taro.getSystemInfoSync().platform == 'ios' ? 'IOS' : 'ANDROID'; //IOS ANDROID
  62. header['X-Lang'] = process.env.TARO_ENV == 'rn' ? 'en' : 'zh' //zh en
  63. header['X-Client-Type'] = process.env.TARO_ENV == 'rn' ? 'APP' : 'WX_APP' //WX_APP APP
  64. header['X-Client-Version'] = process.env.TARO_ENV == 'rn' ? APP_VERSION : WX_VERSION
  65. if (token.length > 0) {
  66. header['Authorization'] = `Bearer ${token}`;
  67. header['Authorization'] = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhY2NvdW50Iiwic3ViIjoiMjZkOGE1YTg0MDMyYmExN2Q4NDk3MTlkNTljNGY1NzgiLCJpc3MiOiJmYXN0Iiwibmlja25hbWUiOiJCSyIsInR5cCI6IkJlYXJlciIsInNlc3Npb25fc3RhdGUiOiJkODczZTBhZGJhY2M2NDQ0OTllYTUwMTUzOGQxZmQ3MSIsImV4cCI6MTc0OTIwMTM2NywiaWF0IjoxNzE3NjY1MzY3fQ.cTQTsHzxBFRSKBztlPKBspg1e9DGT9ppAwb3zD0SDJ0';
  68. }
  69. const timer = setTimeout(() => {
  70. requestTask && requestTask.abort();
  71. console.log('timeout');
  72. if (retryCount < kRetryCount) {
  73. // Retry the request
  74. console.log(`Retrying request (${retryCount + 1}/2)...`);
  75. retryCount++;
  76. performRequest(resolve, reject);
  77. return;
  78. }
  79. if (global.language == 'en') {
  80. ToastUtil.getInstance().showToast(method == 'GET' ?
  81. 'Network connection failed. Please check your network.' :
  82. 'Posting failed. Please check your network.');
  83. }
  84. else {
  85. ToastUtil.getInstance().showToast(method == 'GET' ? '网络连接失败,请检查网络' : '操作失败,请检查网络');
  86. }
  87. reject('timeout');
  88. }, kTimeout);
  89. requestTask = Taro.request({
  90. url: url,
  91. method: method,
  92. header: header,
  93. timeout: kTimeout,
  94. data: data || {},
  95. success: (response: Resp | { [key: string]: any }) => {
  96. clearTimeout(timer);
  97. const { statusCode, data } = response;
  98. if (statusCode != 200) {
  99. console.log(response)
  100. }
  101. if (statusCode >= 200 && statusCode < 300) {
  102. //正常数据返回
  103. var resp = {} as T;
  104. if (response.data) {
  105. resp = response.data as T;
  106. }
  107. resolve(resp);
  108. } else if (statusCode == 401) {
  109. // global.postBtnUpdateStatus('idle')
  110. //未登录或挤下线处理
  111. if (process.env.TARO_ENV == 'weapp') {
  112. Taro.stopPullDownRefresh()
  113. }
  114. else if (process.env.TARO_ENV == 'rn') {
  115. if (url.indexOf('login/password') != -1) {
  116. reject(data);
  117. return;
  118. }
  119. }
  120. if (global.dispatch) {
  121. global.dispatch(logoutSuccess());
  122. }
  123. } else if (statusCode == 500 && response.data.error_code == 'WX_STEP_PARSE_FAIL') {
  124. //单独对计步第一次请求失败处理
  125. resolve(response.data);
  126. } else {
  127. //通用错误处理
  128. Taro.showToast({
  129. icon: 'none',
  130. title: data.error_message,
  131. });
  132. reject(data);
  133. }
  134. },
  135. fail: err => {
  136. if ((err as any).statusCode >= 200 && (err as any).statusCode < 300) {
  137. clearTimeout(timer);
  138. resolve()
  139. return;
  140. }
  141. // global.postBtnUpdateStatus('idle')
  142. // console.log('oppsu');
  143. // clearTimeout(timer);
  144. // reject(err);
  145. },
  146. });
  147. }
  148. return new Promise<T>((resolve, reject) => {
  149. performRequest(resolve, reject);
  150. });
  151. }