axios-wrapper.js 4.0 KB

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