index.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import buildURL from '../helpers/buildURL';
  2. import buildFullPath from '../core/buildFullPath';
  3. import settle from '../core/settle';
  4. import { isUndefined } from '../utils';
  5. /**
  6. * 返回可选值存在的配置
  7. * @param {Array} keys - 可选值数组
  8. * @param {Object} config2 - 配置
  9. * @return {{}} - 存在的配置项
  10. */
  11. const mergeKeys = (keys, config2) => {
  12. const config = {};
  13. keys.forEach((prop) => {
  14. if (!isUndefined(config2[prop])) {
  15. config[prop] = config2[prop];
  16. }
  17. });
  18. return config;
  19. };
  20. export default (config) =>
  21. new Promise((resolve, reject) => {
  22. const fullPath = buildURL(buildFullPath(config.baseURL, config.url), config.params);
  23. const _config = {
  24. url: fullPath,
  25. header: config.header,
  26. complete: (response) => {
  27. config.fullPath = fullPath;
  28. response.config = config;
  29. try {
  30. // 对可能字符串不是json 的情况容错
  31. if (typeof response.data === 'string') {
  32. response.data = JSON.parse(response.data);
  33. }
  34. // eslint-disable-next-line no-empty
  35. } catch (e) {}
  36. settle(resolve, reject, response);
  37. },
  38. };
  39. let requestTask;
  40. if (config.method === 'UPLOAD') {
  41. delete _config.header['content-type'];
  42. delete _config.header['Content-Type'];
  43. const otherConfig = {
  44. // #ifdef MP-ALIPAY
  45. fileType: config.fileType,
  46. // #endif
  47. filePath: config.filePath,
  48. name: config.name,
  49. };
  50. const optionalKeys = [
  51. // #ifdef APP-PLUS || H5
  52. 'files',
  53. // #endif
  54. // #ifdef H5
  55. 'file',
  56. // #endif
  57. // #ifdef H5 || APP-PLUS
  58. 'timeout',
  59. // #endif
  60. 'formData',
  61. ];
  62. requestTask = uni.uploadFile({
  63. ..._config,
  64. ...otherConfig,
  65. ...mergeKeys(optionalKeys, config),
  66. });
  67. } else if (config.method === 'DOWNLOAD') {
  68. // #ifdef H5 || APP-PLUS
  69. if (!isUndefined(config.timeout)) {
  70. _config.timeout = config.timeout;
  71. }
  72. // #endif
  73. requestTask = uni.downloadFile(_config);
  74. } else {
  75. const optionalKeys = [
  76. 'data',
  77. 'method',
  78. // #ifdef H5 || APP-PLUS || MP-ALIPAY || MP-WEIXIN
  79. 'timeout',
  80. // #endif
  81. 'dataType',
  82. // #ifndef MP-ALIPAY
  83. 'responseType',
  84. // #endif
  85. // #ifdef APP-PLUS
  86. 'sslVerify',
  87. // #endif
  88. // #ifdef H5
  89. 'withCredentials',
  90. // #endif
  91. // #ifdef APP-PLUS
  92. 'firstIpv4',
  93. // #endif
  94. ];
  95. requestTask = uni.request({ ..._config, ...mergeKeys(optionalKeys, config) });
  96. }
  97. if (config.getTask) {
  98. config.getTask(requestTask, config);
  99. }
  100. });