axios-wrapper.js 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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. // 过滤key:''的情况
  47. query = _.pickBy(query, val => val !== '');
  48. if (!uri) console.error('uri不能为空');
  49. if (_.isObject(query) && _.isObject(options)) {
  50. const params = query.params ? query.params : query;
  51. options = { ...options, params };
  52. } else if (_.isObject(query) && !query.params) {
  53. options = { params: query };
  54. } else if (_.isObject(query) && query.params) {
  55. options = query;
  56. }
  57. if (!options) options = {};
  58. if (options.params) options.params = trimData(options.params);
  59. const url = AxiosWrapper.merge(uri, options.params);
  60. currentRequests += 1;
  61. // const loadingInstance = Loading.service({ spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.5)' });
  62. try {
  63. const axios = Axios.create({
  64. baseURL: this.baseUrl,
  65. });
  66. const user = localStorage.getItem('user');
  67. if (user) {
  68. axios.defaults.headers.common.Authorization = encodeURI(user);
  69. }
  70. let res = await axios.request({
  71. method: isNullOrUndefined(data) ? 'get' : 'post',
  72. url,
  73. data,
  74. responseType: 'json',
  75. ...options,
  76. });
  77. res = res.data || {};
  78. const { errcode, errmsg, details } = res;
  79. if (errcode) {
  80. console.warn(`[${uri}] fail: ${errcode}-${errmsg} ${details}`);
  81. return res;
  82. }
  83. // unwrap data
  84. if (this.unwrap) {
  85. // res = _.omit(res, ['errcode', 'errmsg', 'details']);
  86. const keys = Object.keys(res);
  87. if (keys.length === 1 && keys.includes('data')) {
  88. res = res.data;
  89. }
  90. }
  91. return res;
  92. } catch (err) {
  93. let errmsg = '接口请求失败,请稍后重试';
  94. if (err.response) {
  95. const { status, data = {} } = err.response;
  96. console.log(err.response);
  97. if (status === 401) errmsg = '用户认证失败,请重新登录';
  98. if (status === 403) errmsg = '当前用户不允许执行该操作';
  99. if (status === 400 && data.errcode) {
  100. const { errcode, errmsg, details } = data;
  101. console.warn(`[${uri}] fail: ${errcode}-${errmsg} ${details}`);
  102. return data;
  103. }
  104. if (data && data.error) {
  105. const { status, error, message } = data;
  106. console.warn(`[${uri}] fail: ${status}: ${error}-${message}`);
  107. return { errcode: status || ErrorCode.SERVICE_FAULT, errmsg: error, details: message };
  108. }
  109. }
  110. console.error(`[AxiosWrapper] 接口请求失败: ${err.config && err.config.url} - ${err.message}`);
  111. return { errcode: ErrorCode.SERVICE_FAULT, errmsg, details: err.message };
  112. } finally {
  113. currentRequests -= 1;
  114. if (currentRequests <= 0) {
  115. currentRequests = 0;
  116. // loadingInstance.close();
  117. }
  118. }
  119. }
  120. }