uni-request-wrapper.js 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. /* eslint-disable no-console */
  2. /* eslint-disable no-param-reassign */
  3. import _, { head } from 'lodash';
  4. import { Util, Error } from 'naf-core';
  5. // import { Indicator } from 'mint-ui';
  6. import util from './user-util';
  7. const { trimData, isNullOrUndefined } = Util;
  8. const { ErrorCode } = Error;
  9. let currentRequests = 0;
  10. export default class UniRequestWrapper {
  11. constructor({ baseUrl = '', unwrap = true } = {}) {
  12. this.baseUrl = baseUrl;
  13. this.unwrap = unwrap;
  14. }
  15. // 替换uri中的参数变量
  16. static merge(uri, query = {}) {
  17. const keys = Object.keys(query);
  18. if (keys.length > 0) uri = `${uri}?`;
  19. else return uri;
  20. const qarr = [];
  21. keys.forEach((key) => {
  22. if (!isNullOrUndefined(query[key])) {
  23. qarr.push(`${key}=${query[key]}`);
  24. }
  25. });
  26. uri = `${uri}${qarr.join('&')}`;
  27. return uri;
  28. }
  29. $get(uri, query, options) {
  30. return this.$request(uri, null, query, options);
  31. }
  32. $post(uri, data = {}, query, options) {
  33. return this.$request(uri, data, query, options);
  34. }
  35. $delete(uri, data = {}, router, query, options = {}) {
  36. options = { ...options, method: 'delete' };
  37. return this.$request(uri, data, query, options, router);
  38. }
  39. async $request(uri, data, query, options) {
  40. // TODO: 合并query和options
  41. if (_.isObject(query) && _.isObject(options)) {
  42. options = { ...options, params: query, method: 'get' };
  43. } else if (_.isObject(query) && !query.params) {
  44. options = { params: query };
  45. } else if (_.isObject(query) && query.params) {
  46. options = query;
  47. }
  48. if (!options) options = {};
  49. if (options.params) options.params = trimData(options.params);
  50. const url = UniRequestWrapper.merge(uri, options.params);
  51. currentRequests += 1;
  52. // Indicator.open({
  53. // spinnerType: 'fading-circle',
  54. // });
  55. try {
  56. const header = {};
  57. if(uni.getStorageSync('token')) {
  58. header.Authorization = uni.getStorageSync('token');
  59. }
  60. let [err, result] = await uni.request({
  61. method: isNullOrUndefined(data) ? 'get' : 'post',
  62. url: `${this.baseUrl}${url}`,
  63. data,
  64. responseType: 'json',
  65. ...options,
  66. header,
  67. });
  68. const { data: res } = result;
  69. const { errcode, errmsg, details } = res;
  70. if (errcode) {
  71. console.warn(`[${uri}] fail: ${errcode}-${errmsg} ${details}`);
  72. return res;
  73. }
  74. let ret = null;
  75. // unwrap data
  76. if (this.unwrap) {
  77. ret = _.omit(res, ['errmsg', 'details']);
  78. const keys = Object.keys(ret);
  79. if (keys.length === 1 && keys.includes('data')) {
  80. ret = res.data;
  81. }
  82. }
  83. return ret;
  84. } catch (err) {
  85. let errmsg = '接口请求失败,请稍后重试';
  86. if (err.response) {
  87. const { status } = err.response;
  88. if (status === 401) errmsg = '用户认证失败,请重新登录';
  89. if (status === 403) errmsg = '当前用户不允许执行该操作';
  90. }
  91. console.error(
  92. `[UniRequestWrapper] 接口请求失败: ${err.config && err.config.url} -
  93. ${err.message}`
  94. );
  95. return { errcode: ErrorCode.SERVICE_FAULT, errmsg, details: err.message };
  96. } finally {
  97. /* eslint-disable */
  98. currentRequests -= 1;
  99. if (currentRequests <= 0) {
  100. currentRequests = 0;
  101. // Indicator.close();
  102. }
  103. }
  104. }
  105. }