axios-wrapper.js 3.3 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. axios.defaults.headers.common.Authorization = util.token;
  66. let res = await axios.request({
  67. method: isNullOrUndefined(data) ? 'get' : 'post',
  68. url,
  69. data,
  70. responseType: 'json',
  71. ...options,
  72. });
  73. res = res.data;
  74. const { errcode, errmsg, details } = res;
  75. if (errcode) {
  76. console.warn(`[${uri}] fail: ${errcode}-${errmsg} ${details}`);
  77. return res;
  78. }
  79. // unwrap data
  80. if (this.unwrap) {
  81. res = _.omit(res, ['details']);
  82. const keys = Object.keys(res);
  83. if (keys.length === 1 && keys.includes('data')) {
  84. res = res.data;
  85. }
  86. }
  87. return res;
  88. } catch (err) {
  89. let errmsg = '接口请求失败,请稍后重试';
  90. if (err.response) {
  91. const { status } = err.response;
  92. if (status === 401) errmsg = '用户认证失败,请重新登录';
  93. if (status === 403) errmsg = '当前用户不允许执行该操作';
  94. }
  95. console.error(
  96. `[AxiosWrapper] 接口请求失败: ${err.config && err.config.url} -
  97. ${err.message}`
  98. );
  99. return { errcode: ErrorCode.SERVICE_FAULT, errmsg, details: err.message };
  100. } finally {
  101. /* eslint-disable */
  102. currentRequests -= 1;
  103. if (currentRequests <= 0) {
  104. currentRequests = 0;
  105. // Indicator.close();
  106. }
  107. }
  108. }
  109. }