axios-wrapper.js 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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. import UserUtil from './user-util';
  8. const { trimData, isNullOrUndefined } = Util;
  9. const { ErrorCode } = Error;
  10. let currentRequests = 0;
  11. export default class AxiosWrapper {
  12. constructor({ baseUrl = '', unwrap = true } = {}) {
  13. this.baseUrl = baseUrl;
  14. this.unwrap = unwrap;
  15. }
  16. // 替换uri中的参数变量
  17. static merge(uri, query = {}) {
  18. if (!uri.includes(':')) {
  19. return uri;
  20. }
  21. const keys = [];
  22. const regexp = /\/:([a-z0-9_]+)/gi;
  23. let res;
  24. // eslint-disable-next-line no-cond-assign
  25. while ((res = regexp.exec(uri)) != null) {
  26. keys.push(res[1]);
  27. }
  28. keys.forEach(key => {
  29. if (!isNullOrUndefined(query[key])) {
  30. uri = uri.replace(`:${key}`, query[key]);
  31. }
  32. });
  33. return uri;
  34. }
  35. $get(uri, query, options) {
  36. return this.$request(uri, null, query, options);
  37. }
  38. $post(uri, data = {}, query, options) {
  39. return this.$request(uri, data, query, options);
  40. }
  41. $delete(uri, data = {}, query, options) {
  42. options = { ...options, method: 'delete' };
  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. options = { ...options, params: query, method: 'get' };
  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. Indicator.open({
  60. spinnerType: 'fading-circle',
  61. });
  62. try {
  63. const axios = Axios.create({
  64. baseURL: this.baseUrl,
  65. });
  66. if (UserUtil.token) {
  67. axios.defaults.headers.common.Authorization = UserUtil.token;
  68. } else if (sessionStorage.getItem('token')) {
  69. axios.defaults.headers.common.Authorization = UserUtil.token;
  70. }
  71. let res = await axios.request({
  72. method: isNullOrUndefined(data) ? 'get' : 'post',
  73. url,
  74. data,
  75. responseType: 'json',
  76. ...options,
  77. });
  78. res = res.data;
  79. const { errcode, errmsg, details } = res;
  80. if (errcode) {
  81. console.warn(`[${uri}] fail: ${errcode}-${errmsg} ${details}`);
  82. return res;
  83. }
  84. // unwrap data
  85. if (this.unwrap) {
  86. res = _.omit(res, ['errcode', 'errmsg', 'details']);
  87. const keys = Object.keys(res);
  88. if (keys.length === 1 && keys.includes('data')) {
  89. res = res.data;
  90. }
  91. }
  92. return res;
  93. } catch (err) {
  94. let errmsg = '接口请求失败,请稍后重试';
  95. if (err.response) {
  96. const { status } = err.response;
  97. if (status === 401) errmsg = '用户认证失败,请重新登录';
  98. if (status === 403) errmsg = '当前用户不允许执行该操作';
  99. }
  100. console.error(`[AxiosWrapper] 接口请求失败: ${err.config && err.config.url} - ${err.message}`);
  101. return { errcode: ErrorCode.SERVICE_FAULT, errmsg, details: err.message };
  102. } finally {
  103. currentRequests -= 1;
  104. if (currentRequests <= 0) {
  105. currentRequests = 0;
  106. Indicator.close();
  107. }
  108. }
  109. }
  110. }