request.ts 5.9 KB

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