purchaseListRequest.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. import fetch from 'dva/fetch';
  2. import { message, notification } from 'antd';
  3. import router from 'umi/router';
  4. import hash from 'hash.js';
  5. import { isAntdPro, getToken, GetTokenFromUrl } from './utils';
  6. // var apiUrl = "http://oraysmart.com:8888"
  7. // var apiUrl = "http://120.55.44.4:8900"
  8. const checkStatus = response => {
  9. if (response.status >= 200 && response.status < 300) {
  10. return response;
  11. }
  12. const error = new Error(response.data);
  13. error.name = response.status;
  14. error.response = response;
  15. throw error;
  16. };
  17. const cachedSave = response => {
  18. if (response.status === 600) return response;
  19. /**
  20. * Clone a response data and store it in sessionStorage
  21. * Does not support data other than json, Cache only json
  22. */
  23. const contentType = response.headers.get('Content-Type');
  24. if (contentType && contentType.match(/application\/json/i)) {
  25. // All data is saved as text
  26. response
  27. .clone()
  28. .text()
  29. .then(() => {
  30. // sessionStorage.setItem(hashcode, content);
  31. // sessionStorage.setItem(`${hashcode}:timestamp`, Date.now());
  32. });
  33. }
  34. return response;
  35. };
  36. /**
  37. * Requests a URL, returning a promise.
  38. *
  39. * @param {string} url The URL we want to request
  40. * @param {object} [option] The options we want to pass to "fetch"
  41. * @return {object} An object containing either "data" or "err"
  42. */
  43. export default function request(url, option, jwt) {
  44. const number = new Date().getTime();
  45. // console.log(API_HOST);
  46. const time = url.indexOf('?') > -1 ? `&time=${number}` : `?time=${number}`;
  47. if (url.indexOf('http://') == -1 && url.indexOf('https://') == -1) {
  48. if (url.indexOf('/api/v') === -1) {
  49. url = `/api/v1${url}${time}`;
  50. }
  51. // API_HOST在config/config.js的define中配置
  52. // url = API_HOST + url
  53. }
  54. let token = getToken();
  55. if (!token) {
  56. token = GetTokenFromUrl();
  57. }
  58. const options = {
  59. expirys: isAntdPro(),
  60. ...option,
  61. };
  62. /**
  63. * Produce fingerprints based on url and parameters
  64. * Maybe url has the same parameters
  65. */
  66. const fingerprint = url + (options.body ? JSON.stringify(options.body) : '');
  67. const hashcode = hash
  68. .sha256()
  69. .update(fingerprint)
  70. .digest('hex');
  71. const defaultOptions = {
  72. credentials: 'include',
  73. };
  74. const newOptions = { ...defaultOptions, ...options };
  75. newOptions.headers = {
  76. ...newOptions.headers,
  77. 'JWT-TOKEN': jwt ? jwt : `${token}`,
  78. };
  79. if (
  80. newOptions.method === 'POST' ||
  81. newOptions.method === 'PUT' ||
  82. newOptions.method === 'DELETE'
  83. ) {
  84. if (!(newOptions.body instanceof FormData)) {
  85. newOptions.headers = {
  86. Accept: 'application/json',
  87. 'Content-Type': 'application/json;charset=utf-8',
  88. ...newOptions.headers,
  89. };
  90. newOptions.body = JSON.stringify(newOptions.body);
  91. } else {
  92. // newOptions.body is FormData
  93. newOptions.headers = {
  94. Accept: 'application/json',
  95. ...newOptions.headers,
  96. };
  97. }
  98. }
  99. const expirys = options.expirys && 60;
  100. // options.expirys !== false, return the cache,
  101. if (options.expirys !== false) {
  102. const cached = sessionStorage.getItem(hashcode);
  103. const whenCached = sessionStorage.getItem(`${hashcode}:timestamp`);
  104. if (cached !== null && whenCached !== null) {
  105. const age = (Date.now() - whenCached) / 1000;
  106. if (age < expirys) {
  107. const response = new Response(new Blob([cached]));
  108. return response.json();
  109. }
  110. sessionStorage.removeItem(hashcode);
  111. sessionStorage.removeItem(`${hashcode}:timestamp`);
  112. }
  113. }
  114. return fetch(url, newOptions)
  115. .then(checkStatus)
  116. .then(response => cachedSave(response, hashcode))
  117. .then(response => {
  118. // DELETE and 204 do not return data by default
  119. // using .json will report an error.
  120. if (response.status === 204) {
  121. return response.text();
  122. }
  123. // if (response.status === 600) {
  124. // return response;
  125. // } else {
  126. return response.json();
  127. // }
  128. })
  129. .then(response => {
  130. if (typeof response === 'string') {
  131. return response;
  132. } else if (response.code !== 200) {
  133. message.error(response.msg);
  134. return false;
  135. } else {
  136. return response;
  137. }
  138. })
  139. .catch(e => {
  140. const status = e.name;
  141. // environment should not be used
  142. if (status === 401 || status === 601 || status === 602 || status === 400) {
  143. // 用户token出错,重定向
  144. notification.error({
  145. message: '错误',
  146. description: 'token失效,请重新登录',
  147. });
  148. router.push('/login');
  149. return;
  150. }
  151. // if (status <= 504 && status > 500 && status !== 600) {
  152. // router.push('/exception/500');
  153. // throw e;
  154. // }
  155. // if (status >= 404 && status < 422) {
  156. // router.push('/exception/404');
  157. // throw e;
  158. // }
  159. // if (status === 600) {
  160. // throw e;
  161. // }
  162. notification.error({
  163. message: '错误',
  164. description: `HTTP请求错误,错误码:${status};接口地址${url}`,
  165. });
  166. throw e;
  167. });
  168. }