axios-wrapper.js 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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 util 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 = {}, router, query, options = {}) {
  42. options = { ...options, method: 'delete' };
  43. return this.$request(uri, data, query, options, router);
  44. }
  45. async $request(uri, data, query, options) {
  46. // TODO: 合并query和options
  47. if (_.isObject(query) && _.isObject(options)) {
  48. options = { ...options, params: query, method: 'get' };
  49. } else if (_.isObject(query) && !query.params) {
  50. options = { params: query };
  51. } else if (_.isObject(query) && query.params) {
  52. options = query;
  53. }
  54. if (!options) options = {};
  55. if (options.params) options.params = trimData(options.params);
  56. const url = AxiosWrapper.merge(uri, options.params);
  57. currentRequests += 1;
  58. // Indicator.open({
  59. // spinnerType: 'fading-circle',
  60. // });
  61. try {
  62. const axios = Axios.create({
  63. baseURL: this.baseUrl,
  64. });
  65. if (util.token) axios.defaults.headers.common.Authorization = `Bearer ${util.token}`;
  66. // axios.defaults.headers.isToken = false;
  67. let res = await axios.request({
  68. method: isNullOrUndefined(data) ? 'get' : 'post',
  69. url,
  70. data,
  71. responseType: 'json',
  72. ...options,
  73. });
  74. res = res.data;
  75. const { errcode, errmsg, details } = res;
  76. if (errcode) {
  77. console.warn(`[${uri}] fail: ${errcode}-${errmsg} ${details}`);
  78. return res;
  79. }
  80. // unwrap data
  81. if (this.unwrap) {
  82. res = _.omit(res, ['errmsg', 'details']);
  83. const keys = Object.keys(res);
  84. if (keys.length === 1 && keys.includes('data')) {
  85. res = res.data;
  86. }
  87. }
  88. return res;
  89. } catch (err) {
  90. let errmsg = '接口请求失败,请稍后重试';
  91. if (err.response) {
  92. const { status } = err.response;
  93. if (status === 401) errmsg = '用户认证失败,请重新登录';
  94. if (status === 403) errmsg = '当前用户不允许执行该操作';
  95. }
  96. console.error(
  97. `[AxiosWrapper] 接口请求失败: ${err.config && err.config.url} -
  98. ${err.message}`
  99. );
  100. return { errcode: ErrorCode.SERVICE_FAULT, errmsg, details: err.message };
  101. } finally {
  102. /* eslint-disable */
  103. currentRequests -= 1;
  104. if (currentRequests <= 0) {
  105. currentRequests = 0;
  106. // Indicator.close();
  107. }
  108. }
  109. }
  110. }