axios-wrapper.js 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. /* eslint-disable no-console */
  2. /* eslint-disable no-param-reassign */
  3. import _ from 'lodash';
  4. import Axios from 'axios';
  5. import { Util, Error } from 'naf-core';
  6. // import { Indicator } from 'mint-ui';
  7. const { trimData, isNullOrUndefined } = Util;
  8. const { ErrorCode } = Error;
  9. let currentRequests = 0;
  10. export default class AxiosWrapper {
  11. constructor({ baseUrl = '', unwrap = true } = {}) {
  12. this.baseUrl = baseUrl;
  13. this.unwrap = unwrap;
  14. }
  15. // 替换uri中的参数变量
  16. static merge(uri, query = {}) {
  17. if (!uri.includes(':')) {
  18. return uri;
  19. }
  20. const keys = [];
  21. const regexp = /\/:([a-z0-9_]+)/gi;
  22. let res;
  23. // eslint-disable-next-line no-cond-assign
  24. while ((res = regexp.exec(uri)) != null) {
  25. keys.push(res[1]);
  26. }
  27. keys.forEach((key) => {
  28. if (!isNullOrUndefined(query[key])) {
  29. uri = uri.replace(`:${key}`, query[key]);
  30. }
  31. });
  32. return uri;
  33. }
  34. $get(uri, query, options) {
  35. return this.$request(uri, null, query, options);
  36. }
  37. $post(uri, data = {}, query, options) {
  38. return this.$request(uri, data, query, options);
  39. }
  40. $delete(uri, data = {}, router, query, options = {}) {
  41. options = { ...options, method: 'delete' };
  42. return this.$request(uri, data, query, options, router);
  43. }
  44. async $request(uri, data, query, options) {
  45. if (query && _.isObject(query)) {
  46. const keys = Object.keys(query);
  47. for (const key of keys) {
  48. if ((query[key] && query[key] === '') || !query[key]) {
  49. delete query[key];
  50. }
  51. }
  52. }
  53. // TODO: 合并query和options
  54. if (_.isObject(query) && _.isObject(options)) {
  55. options = { ...options, params: query, method: 'get' };
  56. } else if (_.isObject(query) && !query.params) {
  57. options = { params: query };
  58. } else if (_.isObject(query) && query.params) {
  59. options = query;
  60. }
  61. if (!options) options = {};
  62. if (options.params) options.params = trimData(options.params);
  63. const url = AxiosWrapper.merge(uri, options.params);
  64. currentRequests += 1;
  65. // Indicator.open({
  66. // spinnerType: 'fading-circle',
  67. // });
  68. try {
  69. const axios = Axios.create({
  70. baseURL: this.baseUrl,
  71. });
  72. // if (util.token && util.token !== null) axios.defaults.headers.common.Authorization = util.token;
  73. const token = sessionStorage.getItem('token');
  74. const apiToken = sessionStorage.getItem('apiToken');
  75. if (token) axios.defaults.headers.common['user-token'] = token;
  76. if (apiToken) axios.defaults.headers.common['api-token'] = apiToken;
  77. let res = await axios.request({
  78. method: isNullOrUndefined(data) ? 'get' : 'post',
  79. url,
  80. data,
  81. responseType: 'json',
  82. ...options,
  83. });
  84. res = res.data;
  85. const { errcode, errmsg, details } = res;
  86. if (errcode) {
  87. console.warn(`[${uri}] fail: ${errcode}-${errmsg} ${details}`);
  88. return res;
  89. }
  90. // unwrap data
  91. if (this.unwrap) {
  92. res = _.omit(res, ['errmsg', 'details']);
  93. const keys = Object.keys(res);
  94. if (keys.length === 1 && keys.includes('data')) {
  95. res = res.data;
  96. }
  97. }
  98. // 处理apiToken
  99. const { apiToken: at, ...others } = res;
  100. if (at) sessionStorage.setItem('apiToken', at);
  101. return others;
  102. } catch (err) {
  103. let errmsg = '接口请求失败,请稍后重试';
  104. if (err.response) {
  105. const { status } = err.response;
  106. if (status === 401) errmsg = '用户认证失败,请重新登录';
  107. if (status === 403) errmsg = '当前用户不允许执行该操作';
  108. }
  109. console.error(
  110. `[AxiosWrapper] 接口请求失败: ${err.config && err.config.url} -
  111. ${err.message}`
  112. );
  113. return { errcode: ErrorCode.SERVICE_FAULT, errmsg, details: err.message };
  114. } finally {
  115. /* eslint-disable */
  116. currentRequests -= 1;
  117. if (currentRequests <= 0) {
  118. currentRequests = 0;
  119. // Indicator.close();
  120. }
  121. }
  122. }
  123. }