axios-wrapper.js 3.3 KB

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