axios-wrapper.js 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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. 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. $delete(uri, query, options = {}) {
  38. return this.$request(uri, null, query, { ...options, method: 'delete' });
  39. }
  40. $post(uri, data = {}, query, options) {
  41. return this.$request(uri, data, query, options);
  42. }
  43. async $request(uri, data, query, options) {
  44. // 过滤key:''的情况
  45. query = _.pickBy(query, val => val !== '');
  46. if (!uri) console.error('uri不能为空');
  47. if (_.isObject(query) && _.isObject(options)) {
  48. const params = query.params ? query.params : query;
  49. options = { ...options, params };
  50. } else if (_.isObject(query) && !query.params) {
  51. options = { params: query };
  52. } else if (_.isObject(query) && query.params) {
  53. options = query;
  54. }
  55. if (!options) options = {};
  56. if (options.params) options.params = trimData(options.params);
  57. const url = AxiosWrapper.merge(uri, options.params);
  58. currentRequests += 1;
  59. // const loadingInstance = Loading.service({ spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.5)' });
  60. try {
  61. const axios = Axios.create({
  62. baseURL: this.baseUrl,
  63. });
  64. const user = localStorage.getItem('user');
  65. if (user) {
  66. axios.defaults.headers.common.Authorization = encodeURI(user);
  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. if (status === 401) errmsg = '用户认证失败,请重新登录';
  95. if (status === 403) errmsg = '当前用户不允许执行该操作';
  96. if (status === 400 && data.errcode) {
  97. const { errcode, errmsg, details } = data;
  98. console.warn(`[${uri}] fail: ${errcode}-${errmsg} ${details}`);
  99. return data;
  100. }
  101. if (data && data.error) {
  102. const { status, error, message } = data;
  103. console.warn(`[${uri}] fail: ${status}: ${error}-${message}`);
  104. return { errcode: status || ErrorCode.SERVICE_FAULT, errmsg: error, details: message };
  105. }
  106. }
  107. console.error(`[AxiosWrapper] 接口请求失败: ${err.config && err.config.url} - ${err.message}`);
  108. return { errcode: ErrorCode.SERVICE_FAULT, errmsg, details: err.message };
  109. } finally {
  110. currentRequests -= 1;
  111. if (currentRequests <= 0) {
  112. currentRequests = 0;
  113. // loadingInstance.close();
  114. }
  115. }
  116. }
  117. }