UNPKG

@livelybone/easy-request

Version:

A easy-to-use http request library to support all javascript runtime environments. 一个以支持所有JavaScript运行环境为目的、简单易用的http请求库。

1,651 lines (1,365 loc) 46.7 kB
/** * Bundle of @livelybone/easy-request * Generated: 2020-07-29 * Version: 1.9.1 * License: MIT * Author: 2631541504@qq.com */ import { blobToBase64 } from 'base64-blob'; import { objectToFormData } from 'object-to-formdata'; import { stringify } from 'qs'; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var EngineName; (function (EngineName) { EngineName["WX"] = "wx"; EngineName["MY"] = "my"; EngineName["XHR"] = "xhr"; EngineName["Fetch"] = "fetch"; })(EngineName || (EngineName = {})); function joinUrl(baseUrl, url, data) { var $url = /^https?:\/\//.test(url) ? url : "".concat(baseUrl, "///").concat(url).replace(/\/{3,}/g, '/'); if (!data) return $url; return "".concat($url, "?&").concat(stringify(data)).replace(/\?+&+/, '?'); } function getBlobUrl(blob) { var gntUrl = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (!blob || !gntUrl) return Promise.resolve(''); if (URL && URL.createObjectURL) { var url = URL.createObjectURL(blob); console.warn("ObjectURL `".concat(url, "` has been created in the app, make sure you will revoke it at the right time in you code by script `URL.revokeObjectURL(").concat(url, ")`")); return Promise.resolve(url); } return blobToBase64(blob); } function strJsonParse(str) { if (!str) return str; try { return JSON.parse(str); } catch (e) { return str; } } function dealRequestData(data, contentType, convertFormDataOptions) { if (!data) return null; if (data instanceof FormData) return data; var _ref = convertFormDataOptions || {}, customConvertFn = _ref.customConvertFn, restOptions = _objectWithoutProperties(_ref, ["customConvertFn"]); return contentType === 'multipart/form-data' ? customConvertFn ? customConvertFn(data) : objectToFormData(data, restOptions) : contentType === 'application/json' ? JSON.stringify(data) : stringify(data); } function mergeHeaders(tHeaders, headers) { var $headers = headers || tHeaders; return Object.keys($headers).reduce(function (pre, k) { if (k.toLowerCase() !== 'content-type') pre[k] = $headers[k];else pre['Content-Type'] = $headers[k]; return pre; }, headers ? mergeHeaders(tHeaders) : {}); } function statusValidator(status) { return status === undefined || status >= 200 && status < 300; } function mergeConfig(conf1, conf2) { var config = _objectSpread2(_objectSpread2(_objectSpread2({}, conf1), conf2), {}, { headers: mergeHeaders(conf1.headers, conf2 && conf2.headers), statusValidator: conf2 && conf2.statusValidator || conf1.statusValidator || statusValidator }); config.method = config.method.toUpperCase(); if (typeof FormData !== 'undefined' && config.data instanceof FormData) { delete config.headers['Content-Type']; } return config; } function getMsg(obj) { var defaultMsg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; if (_typeof(obj) === 'object' && obj !== null) { var keys = ['message', 'msg', 'error', 'err', 'errMessage', 'errMsg', 'errorMessage', 'errorMsg']; var message = defaultMsg; keys.some(function (k) { var msg = obj[k] || obj[k.toLowerCase()]; if (msg) message = msg; return !!msg; }); return message; } return obj || defaultMsg; } function getFileName(headers) { var disposition = headers && headers['content-disposition']; if (!disposition) return ''; var matched = disposition.match(/(file)?name\s*=\s*([^=]+)($|,)/); return matched && matched[2] || ''; } var RequestPromise = /*#__PURE__*/function () { function RequestPromise(cb) { _classCallCheck(this, RequestPromise); _defineProperty(this, "promise", void 0); _defineProperty(this, "abort", function () {}); this.promise = new Promise(cb); } _createClass(RequestPromise, [{ key: "then", value: function then(onfulfilled, onrejected) { var _this = this; var pro = new RequestPromise(function (res, rej) { _this.promise.then(onfulfilled, onrejected).then(res, rej); }); pro.abort = this.abort; return pro; } }, { key: "catch", value: function _catch(onrejected) { var _this2 = this; var pro = new RequestPromise(function (res, rej) { _this2.promise.catch(onrejected).then(res, rej); }); pro.abort = this.abort; return pro; } }, { key: "finally", value: function _finally(cb) { var _this3 = this; var pro = new RequestPromise(function (res, rej) { _this3.promise.then(function (val) { cb(); res(val); }, function (e) { cb(); rej(e); }); }); pro.abort = this.abort; return pro; } }]); return RequestPromise; }(); var BaseEngine = function BaseEngine(config) { _classCallCheck(this, BaseEngine); _defineProperty(this, "config", void 0); _defineProperty(this, "requestInstance", void 0); _defineProperty(this, "requestTask", void 0); _defineProperty(this, "response", { url: '', data: null, statusCode: 0, headers: {} }); _defineProperty(this, "aborted", false); this.config = config; }; function getOptions(config, requestTask) { var options = { url: config.url, method: config.method.toUpperCase(), headers: config.headers, header: config.headers, signal: requestTask && requestTask.signal, mode: config.mode || 'cors', credentials: config.withCredentials ? 'include' : 'omit', redirect: config.redirect || 'follow', cache: 'default', referrer: 'no-referrer' }; if (['GET', 'HEAD'].includes(options.method)) { delete config.headers['Content-Type']; options.url = joinUrl('/', config.url, config.data); } else { var contentType = config.headers['Content-Type']; options.body = dealRequestData(config.data, contentType, config.convertFormDataOptions); if (contentType === 'multipart/form-data' || !options.body) { delete config.headers['Content-Type']; } } return options; } var FetchBase = /*#__PURE__*/function (_BaseEngine) { _inherits(FetchBase, _BaseEngine); var _super = _createSuper(FetchBase); function FetchBase(config) { var _this; _classCallCheck(this, FetchBase); _this = _super.call(this, config); _defineProperty(_assertThisInitialized(_this), "name", EngineName.Fetch); if (typeof fetch === 'function') _this.requestInstance = function () { return fetch.apply(void 0, arguments); }; if (typeof AbortController !== 'undefined') _this.requestTask = new AbortController(); return _this; } _createClass(FetchBase, [{ key: "abort", value: function abort() { if (!this.requestTask) { throw new Error('AbortController api does not exist!'); } this.requestTask.abort(); } }, { key: "getConfig", value: function getConfig() { return getOptions(this.config, this.requestTask); } }]); return FetchBase; }(BaseEngine); function dealRequest(ctx) { var _ctx$getConfig = ctx.getConfig(), url = _ctx$getConfig.url, config = _objectWithoutProperties(_ctx$getConfig, ["url"]); return ctx.requestInstance(url, config).then(function (response) { ctx.response = { url: response.url || url, statusCode: response.status || 200, headers: response.headers, data: null }; var responseType = ctx.config.responseType; return Promise.resolve(responseType === 'blob' ? response.blob() : responseType === 'json' ? response.json() : responseType === 'arraybuffer' ? response.arrayBuffer() : response.text()).catch(function () { return null; }).then(function (data) { ctx.response.data = data; return ctx.response; }); }); } var Fetch = /*#__PURE__*/function (_FetchBase) { _inherits(Fetch, _FetchBase); var _super2 = _createSuper(Fetch); function Fetch() { _classCallCheck(this, Fetch); return _super2.apply(this, arguments); } _createClass(Fetch, [{ key: "open", value: function open() { if (!this.requestInstance) { return Promise.reject(new Error('fetch api does not exist, please check the environment!')); } return dealRequest(this); } }]); return Fetch; }(FetchBase); var FetchDownload = /*#__PURE__*/function (_FetchBase2) { _inherits(FetchDownload, _FetchBase2); var _super3 = _createSuper(FetchDownload); function FetchDownload() { _classCallCheck(this, FetchDownload); return _super3.apply(this, arguments); } _createClass(FetchDownload, [{ key: "open", value: function open() { var _this2 = this; if (!this.requestInstance) { return Promise.reject(new Error('fetch api does not exist, please check the environment!')); } if (this.config.onDownloadProgress) { console.warn(new Error('Download progress does not support yet in fetch')); } var _this$getConfig = this.getConfig(), url = _this$getConfig.url, config = _objectWithoutProperties(_this$getConfig, ["url"]); return this.requestInstance(url, config).then(function (response) { var headers = _toConsumableArray(response.headers.entries()).reduce(function (pre, _ref) { var _ref2 = _slicedToArray(_ref, 2), k = _ref2[0], val = _ref2[1]; return _objectSpread2(_objectSpread2({}, pre), {}, _defineProperty({}, k, val)); }, {}); return response.blob().then(function (blob) { return getBlobUrl(blob, !!_this2.config.filePath).then(function (tempFilePath) { var filename = getFileName(headers); blob.name = filename; _this2.response = { url: response.url || url, blob: blob, tempFilePath: tempFilePath, filePath: _this2.config.filePath, statusCode: response.status || 200, headers: headers, filename: filename }; return _this2.response; }); }); }); } }]); return FetchDownload; }(FetchBase); var FetchUpload = /*#__PURE__*/function (_FetchBase3) { _inherits(FetchUpload, _FetchBase3); var _super4 = _createSuper(FetchUpload); function FetchUpload() { _classCallCheck(this, FetchUpload); return _super4.apply(this, arguments); } _createClass(FetchUpload, [{ key: "open", value: function open() { if (!this.requestInstance) { return Promise.reject(new Error('fetch api does not exist, please check the environment!')); } if (this.config.onUploadProgress) { console.warn(new Error('Download progress does not support yet in fetch')); } return dealRequest(this); } }, { key: "getConfig", value: function getConfig() { return getOptions(_objectSpread2(_objectSpread2({}, this.config), {}, { data: _objectSpread2(_objectSpread2({}, this.config.extraData), {}, _defineProperty({}, this.config.fileKey, this.config.file)), method: 'POST', responseType: 'json', withCredentials: true, headers: _objectSpread2(_objectSpread2({}, this.config.headers), {}, { 'Content-Type': 'multipart/form-data' }) }), this.requestTask); } }]); return FetchUpload; }(FetchBase); var MYBase = /*#__PURE__*/function (_BaseEngine) { _inherits(MYBase, _BaseEngine); var _super = _createSuper(MYBase); function MYBase(config) { var _this; _classCallCheck(this, MYBase); _this = _super.call(this, config); _defineProperty(_assertThisInitialized(_this), "name", EngineName.MY); if (my && (my.request || my.httpRequest)) { _this.requestInstance = my.request || my.httpRequest; } return _this; } _createClass(MYBase, [{ key: "abort", value: function abort() { if (!this.requestTask) { throw new Error('Please call abort after request opened'); } this.requestTask.abort(); } }]); return MYBase; }(BaseEngine); var MY = /*#__PURE__*/function (_MYBase) { _inherits(MY, _MYBase); var _super2 = _createSuper(MY); function MY() { _classCallCheck(this, MY); return _super2.apply(this, arguments); } _createClass(MY, [{ key: "getConfig", value: function getConfig() { return { url: this.config.url, method: this.config.method.toUpperCase(), data: this.config.data, headers: this.config.headers, header: this.config.headers, timeout: this.config.timeout, dataType: this.config.responseType }; } }, { key: "open", value: function open() { var _this2 = this; if (!this.requestInstance) { return Promise.reject(new Error('`my.request` and `my.httpRequest` does not exist, please check the environment!')); } if (['blob', 'document'].includes(this.config.responseType)) { return Promise.reject(new Error("The dataType `".concat(this.config.responseType, "` is not supported in my"))); } return new Promise(function (resolve, reject) { _this2.requestTask = _this2.requestInstance(_objectSpread2(_objectSpread2({}, _this2.getConfig()), {}, { success: function success(res) { _this2.response = _objectSpread2(_objectSpread2({}, res), {}, { url: res.url || _this2.config.url, data: strJsonParse(res.data), statusCode: res.statusCode || res.status || 200, headers: res.header || res.headers }); resolve(_this2.response); }, failed: reject })); }); } }]); return MY; }(MYBase); function bindProgress(task, onProgress) { task.onProgressUpdate(function (_ref) { var progress = _ref.progress, totalBytesWritten = _ref.totalBytesWritten, totalBytesExpectedToWrite = _ref.totalBytesExpectedToWrite; onProgress({ progress: progress, total: totalBytesExpectedToWrite, transmitted: totalBytesWritten }); }); } var MYDownload = /*#__PURE__*/function (_MYBase2) { _inherits(MYDownload, _MYBase2); var _super3 = _createSuper(MYDownload); function MYDownload() { _classCallCheck(this, MYDownload); return _super3.apply(this, arguments); } _createClass(MYDownload, [{ key: "getConfig", value: function getConfig() { return { url: this.config.url, header: this.config.headers, headers: this.config.headers }; } }, { key: "open", value: function open() { var _this3 = this; if (!this.requestInstance) { return Promise.reject(new Error('`my.downloadFile` does not exist, please check the environment!')); } return new Promise(function (resolve, reject) { _this3.requestTask = _this3.requestInstance(_objectSpread2(_objectSpread2({}, _this3.getConfig()), {}, { success: function success(res) { _this3.response = _objectSpread2(_objectSpread2({}, res), {}, { url: res.url || _this3.config.url, tempFilePath: res.tempFilePath, filePath: _this3.config.filePath, statusCode: res.statusCode || res.status || 200 }); resolve(_this3.response); }, failed: reject })); var onDownloadProgress = _this3.config.onDownloadProgress; if (onDownloadProgress) { if (!_this3.requestTask.onProgressUpdate) { console.warn('`my.downloadFile` does not support download progress event in the current version!'); } else bindProgress(_this3.requestTask, onDownloadProgress); } }); } }]); return MYDownload; }(MYBase); var MYUpload = /*#__PURE__*/function (_MYBase3) { _inherits(MYUpload, _MYBase3); var _super4 = _createSuper(MYUpload); function MYUpload() { _classCallCheck(this, MYUpload); return _super4.apply(this, arguments); } _createClass(MYUpload, [{ key: "getConfig", value: function getConfig() { return { url: this.config.url, filePath: this.config.file, fileName: this.config.fileKey, fileType: this.config.fileType || 'image', header: this.config.headers, headers: this.config.headers, formData: this.config.extraData }; } }, { key: "open", value: function open() { var _this4 = this; if (!this.requestInstance) { return Promise.reject(new Error('`my.uploadFile` does not exist, please check the environment!')); } return new Promise(function (resolve, reject) { _this4.requestTask = _this4.requestInstance(_objectSpread2(_objectSpread2({}, _this4.getConfig()), {}, { success: function success(res) { _this4.response = _objectSpread2(_objectSpread2({}, res), {}, { url: res.url || _this4.config.url, data: strJsonParse(res.data), headers: res.header || res.headers, statusCode: res.statusCode || res.status || 200 }); resolve(_this4.response); }, fail: reject })); var onUploadProgress = _this4.config.onUploadProgress; if (onUploadProgress) { if (!_this4.requestTask.onProgressUpdate) { console.warn('`my.uploadFile` does not support upload progress event in the current version!'); } else bindProgress(_this4.requestTask, onUploadProgress); } }); } }]); return MYUpload; }(MYBase); var WXBase = /*#__PURE__*/function (_BaseEngine) { _inherits(WXBase, _BaseEngine); var _super = _createSuper(WXBase); function WXBase(config) { var _this; _classCallCheck(this, WXBase); _this = _super.call(this, config); _defineProperty(_assertThisInitialized(_this), "name", EngineName.WX); if (wx && wx.request) { _this.requestInstance = wx.request; } return _this; } _createClass(WXBase, [{ key: "abort", value: function abort() { if (!this.requestTask) { throw new Error('Please call abort after request opened'); } this.requestTask.abort(); } }]); return WXBase; }(BaseEngine); var WX = /*#__PURE__*/function (_WXBase) { _inherits(WX, _WXBase); var _super2 = _createSuper(WX); function WX() { _classCallCheck(this, WX); return _super2.apply(this, arguments); } _createClass(WX, [{ key: "getConfig", value: function getConfig() { return { url: this.config.url, data: this.config.data, method: this.config.method, dataType: this.config.responseType, timeout: this.config.timeout, header: this.config.headers, headers: this.config.headers }; } }, { key: "open", value: function open() { var _this2 = this; if (!this.requestInstance) { return Promise.reject(new Error('`wx.request` does not exist, please check the environment!')); } if (this.config.responseType && !['json', 'text'].includes(this.config.responseType)) { console.warn(new Error("The dataType `".concat(this.config.responseType, "` is not supported in wx"))); } return new Promise(function (resolve, reject) { _this2.requestTask = _this2.requestInstance(_objectSpread2(_objectSpread2({}, _this2.getConfig()), {}, { success: function success(res) { _this2.response = _objectSpread2(_objectSpread2({}, res), {}, { url: res.url || _this2.config.url, data: strJsonParse(res.data), headers: res.header || res.headers, statusCode: res.statusCode || 200 }); resolve(_this2.response); }, failed: reject })); }); } }]); return WX; }(WXBase); function bindProgress$1(task, onProgress) { var handler = function handler(_ref) { var progress = _ref.progress, totalBytesWritten = _ref.totalBytesWritten, totalBytesExpectedToWrite = _ref.totalBytesExpectedToWrite; onProgress({ progress: progress, total: totalBytesExpectedToWrite, transmitted: totalBytesWritten }); if (totalBytesWritten - totalBytesExpectedToWrite >= 0) { task.offProgressUpdate(handler); } }; task.onProgressUpdate(handler); } var WXDownload = /*#__PURE__*/function (_WXBase2) { _inherits(WXDownload, _WXBase2); var _super3 = _createSuper(WXDownload); function WXDownload() { _classCallCheck(this, WXDownload); return _super3.apply(this, arguments); } _createClass(WXDownload, [{ key: "getConfig", value: function getConfig() { return { url: this.config.url, timeout: this.config.timeout, header: this.config.headers, headers: this.config.headers, filePath: this.config.filePath }; } }, { key: "open", value: function open() { var _this3 = this; if (!this.requestInstance) { return Promise.reject(new Error('`wx.downloadFile` does not exist, please check the environment!')); } return new Promise(function (resolve, reject) { _this3.requestTask = _this3.requestInstance(_objectSpread2(_objectSpread2({}, _this3.getConfig()), {}, { success: function success(res) { _this3.response = _objectSpread2(_objectSpread2({}, res), {}, { url: res.url || _this3.config.url, tempFilePath: res.tempFilePath, filePath: _this3.config.filePath, statusCode: res.statusCode || 200 }); resolve(_this3.response); }, failed: reject })); var onDownloadProgress = _this3.config.onDownloadProgress; if (onDownloadProgress) { if (!_this3.requestTask.onProgressUpdate) { console.warn('`wx.downloadFile` does not support download progress event in the current version!'); } else bindProgress$1(_this3.requestTask, onDownloadProgress); } }); } }]); return WXDownload; }(WXBase); var WXUpload = /*#__PURE__*/function (_WXBase3) { _inherits(WXUpload, _WXBase3); var _super4 = _createSuper(WXUpload); function WXUpload() { _classCallCheck(this, WXUpload); return _super4.apply(this, arguments); } _createClass(WXUpload, [{ key: "getConfig", value: function getConfig() { return { url: this.config.url, timeout: this.config.timeout, header: this.config.headers, headers: this.config.headers }; } }, { key: "open", value: function open() { var _this4 = this; if (!this.requestInstance) { return Promise.reject(new Error('`wx.request` does not exist, please check the environment!')); } return new Promise(function (resolve, reject) { _this4.requestTask = _this4.requestInstance(_objectSpread2(_objectSpread2({}, _this4.getConfig()), {}, { success: function success(res) { _this4.response = _objectSpread2(_objectSpread2({}, res), {}, { url: res.url || _this4.config.url, data: strJsonParse(res.data), headers: res.header || res.headers, statusCode: res.statusCode || 200 }); resolve(_this4.response); }, failed: reject })); var onUploadProgress = _this4.config.onUploadProgress; if (onUploadProgress) { if (!_this4.requestTask.onProgressUpdate) { console.warn('`wx.uploadFile` does not support upload progress event in the current version!'); } else bindProgress$1(_this4.requestTask, onUploadProgress); } }); } }]); return WXUpload; }(WXBase); function createXhr() { if (XMLHttpRequest) { // code for all new browsers return new XMLHttpRequest(); } if (ActiveXObject) { // code for IE5 and I E6 return new ActiveXObject('Microsoft.XMLHTTP'); } return null; } function openXhr(xhr, config, responseMap) { if (!xhr) { return Promise.reject(new Error('The environment does not support XHR')); } return new Promise(function (resolve, reject) { xhr.onreadystatechange = function () { if (xhr.readyState === 4) { // 4 = "loaded" resolve(responseMap(xhr.response)); } }; if (config.responseType) xhr.responseType = config.responseType.toLowerCase(); if (config.withCredentials) xhr.withCredentials = config.withCredentials; if (config.timeout) xhr.timeout = config.timeout; xhr.ontimeout = function () { return reject(new Error('Request time out')); }; if (config.onDownloadProgress) xhr.onprogress = function (_ref) { var total = _ref.total, loaded = _ref.loaded; return config.onDownloadProgress({ total: total, transmitted: loaded, progress: loaded / total }); }; if (config.onUploadProgress) { xhr.upload.onprogress = function (_ref2) { var total = _ref2.total, loaded = _ref2.loaded; return config.onUploadProgress({ total: total, transmitted: loaded, progress: loaded / total }); }; } var url = config.url; var data = null; if (config.method === 'GET') { delete config.headers['Content-Type']; url = joinUrl('', config.url, config.data); } else { data = dealRequestData(config.data, config.headers['Content-Type'], config.convertFormDataOptions); if (config.headers['Content-Type'] === 'multipart/form-data' || !data) delete config.headers['Content-Type']; } xhr.open(config.method, url, true); Object.keys(config.headers).forEach(function (k) { xhr.setRequestHeader(k, config.headers[k]); }); xhr.send(data); }); } function dealHeadersStr(headers) { return headers.split(/[\n\r]+/g).filter(Boolean).reduce(function (pre, header) { var _header$split = header.split(': '), _header$split2 = _slicedToArray(_header$split, 2), k = _header$split2[0], value = _header$split2[1]; return _objectSpread2(_objectSpread2({}, pre), {}, _defineProperty({}, k, value)); }, {}); } var XhrBase = /*#__PURE__*/function (_BaseEngine) { _inherits(XhrBase, _BaseEngine); var _super = _createSuper(XhrBase); function XhrBase(config) { var _this; _classCallCheck(this, XhrBase); _this = _super.call(this, config); _defineProperty(_assertThisInitialized(_this), "name", EngineName.XHR); _this.requestInstance = createXhr(); _this.requestTask = _this.requestInstance; return _this; } _createClass(XhrBase, [{ key: "abort", value: function abort() { this.requestTask.abort(); } }]); return XhrBase; }(BaseEngine); var Xhr = /*#__PURE__*/function (_XhrBase) { _inherits(Xhr, _XhrBase); var _super2 = _createSuper(Xhr); function Xhr() { _classCallCheck(this, Xhr); return _super2.apply(this, arguments); } _createClass(Xhr, [{ key: "open", value: function open() { var _this2 = this; return openXhr(this.requestInstance, this.config, function (res) { _this2.response = { url: _this2.config.url, data: res, statusCode: _this2.requestInstance.status, headers: dealHeadersStr(_this2.requestInstance.getAllResponseHeaders()) }; return _this2.response; }); } }]); return Xhr; }(XhrBase); var XhrDownload = /*#__PURE__*/function (_XhrBase2) { _inherits(XhrDownload, _XhrBase2); var _super3 = _createSuper(XhrDownload); function XhrDownload() { _classCallCheck(this, XhrDownload); return _super3.apply(this, arguments); } _createClass(XhrDownload, [{ key: "open", value: function open() { var _this3 = this; return openXhr(this.requestInstance, _objectSpread2(_objectSpread2({}, this.config), {}, { method: 'GET', responseType: 'blob', withCredentials: this.config.withCredentials || false }), function (blob) { return getBlobUrl(blob, !!_this3.config.filePath).then(function (tempFilePath) { var headers = dealHeadersStr(_this3.requestInstance.getAllResponseHeaders()); var filename = getFileName(headers); if (blob) blob.name = filename; _this3.response = { url: _this3.config.url, tempFilePath: tempFilePath, filePath: _this3.config.filePath, statusCode: _this3.requestInstance.status, blob: blob, headers: dealHeadersStr(_this3.requestInstance.getAllResponseHeaders()), filename: filename }; return _this3.response; }); }); } }]); return XhrDownload; }(XhrBase); var XhrUpload = /*#__PURE__*/function (_XhrBase3) { _inherits(XhrUpload, _XhrBase3); var _super4 = _createSuper(XhrUpload); function XhrUpload() { _classCallCheck(this, XhrUpload); return _super4.apply(this, arguments); } _createClass(XhrUpload, [{ key: "open", value: function open() { var _this4 = this; return openXhr(this.requestInstance, _objectSpread2(_objectSpread2({}, this.config), {}, { data: _objectSpread2(_objectSpread2({}, this.config.extraData), {}, _defineProperty({}, this.config.fileKey, this.config.file)), method: 'POST', responseType: 'json', withCredentials: this.config.withCredentials || false, headers: _objectSpread2(_objectSpread2({}, this.config.headers), {}, { 'Content-Type': 'multipart/form-data' }) }), function (res) { _this4.response = { url: _this4.config.url, data: res, statusCode: _this4.requestInstance.status || 200, headers: dealHeadersStr(_this4.requestInstance.getAllResponseHeaders()) }; return _this4.response; }); } }]); return XhrUpload; }(XhrBase); var Http = /*#__PURE__*/function () { function Http() { var _this = this; var engineName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : EngineName.XHR; var config = arguments.length > 1 ? arguments[1] : undefined; _classCallCheck(this, Http); _defineProperty(this, "engineName", EngineName.XHR); _defineProperty(this, "config", { baseURL: '', method: 'GET', timeout: 30000, responseType: 'json', withCredentials: false, headers: { 'content-type': 'application/x-www-form-urlencoded' } }); _defineProperty(this, "interceptors", { request: { interceptors: [], use: function use(cb) { _this.interceptors.request.interceptors.push(cb); } }, response: { interceptors: { resolves: [], rejects: [] }, use: function use(resCb, errCb) { if (resCb) _this.interceptors.response.interceptors.resolves.push(resCb); if (errCb) _this.interceptors.response.interceptors.rejects.push(errCb); } } }); this.engineName = engineName; this.config = mergeConfig(this.config, config); } _createClass(Http, [{ key: "calcConfig", value: function calcConfig(config) { var _this2 = this; var $config = mergeConfig(this.config, config); var $url = joinUrl($config.baseURL, config.url); var abort = function abort() {}; var conf = new Promise(function (res, rej) { _this2.interceptors.request.interceptors.reduce(function (pre, cb) { return pre.then(function (it) { $config = it; return Promise.resolve(cb(it)); }); }, Promise.resolve(_objectSpread2(_objectSpread2({}, $config), {}, { url: $url }))).then(res); abort = function abort() { return rej(Http.createError({ $request: { config: $config, name: _this2.engineName, requestInstance: null, requestTask: null, response: null, aborted: true }, data: null, statusCode: 0, url: $url, headers: {} }, undefined, 'Request aborted while processing configuration')); }; }); return { config: conf, abort: abort }; } }, { key: "getRequestInstance", value: function getRequestInstance(config) { return this.engineName === EngineName.WX ? new WX(config) : this.engineName === EngineName.MY ? new MY(config) : this.engineName === EngineName.Fetch ? new Fetch(config) : new Xhr(config); } }, { key: "getDownloadInstance", value: function getDownloadInstance(config) { return this.engineName === EngineName.WX ? new WXDownload(config) : this.engineName === EngineName.MY ? new MYDownload(config) : this.engineName === EngineName.Fetch ? new FetchDownload(config) : new XhrDownload(config); } }, { key: "getUploadInstance", value: function getUploadInstance(config) { return this.engineName === EngineName.WX ? new WXUpload(config) : this.engineName === EngineName.MY ? new MYUpload(config) : this.engineName === EngineName.Fetch ? new FetchUpload(config) : new XhrUpload(config); } }, { key: "checkStatus", value: function checkStatus(res) { if (!this.config.statusValidator(res.statusCode)) { return Promise.reject(res); } return Promise.resolve(res); } }, { key: "request", value: function request(url, data, options) { var _this3 = this; var interceptors = this.interceptors.response.interceptors; var _this$calcConfig = this.calcConfig(_objectSpread2(_objectSpread2({}, options), {}, { url: url, data: data })), conf = _this$calcConfig.config, abort = _this$calcConfig.abort; var $res; var $rej; var req = new RequestPromise(function (res, rej) { $res = res; $rej = rej; }); req.abort = abort; conf.then(function (config) { var request = _this3.getRequestInstance(config); req.abort = function () { request.abort(); request.aborted = true; }; var resolve = function resolve(response) { return interceptors.resolves.reduce(function (pre, cb) { return pre.then(cb).then(function (res) { return Http.dealResponse(res, request); }); }, Promise.resolve(_this3.checkStatus(Http.dealResponse(response, request)))); }; var reject = function reject(e) { return interceptors.rejects.reduce(function (pre, cb) { return pre.then(function (res) { return Promise.reject(res); }).catch(function (result) { return cb(Http.createError(result, request)); }); }, Promise.resolve(Http.createError(e, request))).then(function (res) { return Promise.reject(res); }); }; request.open().then(resolve).then($res).catch(reject).catch($rej); }).catch($rej); return req; } /** * 对应微信/支付宝小程序的 downloadFile * */ }, { key: "downloadFile", value: function downloadFile(options) { var _this4 = this; var _this$calcConfig2 = this.calcConfig(options), conf = _this$calcConfig2.config, abort = _this$calcConfig2.abort; var $res; var $rej; var req = new RequestPromise(function (res, rej) { $res = res; $rej = rej; }); req.abort = abort; conf.then(function (config) { var request = _this4.getDownloadInstance(config); req.abort = function () { request.abort(); request.aborted = true; }; request.open().then(function (res) { return _this4.checkStatus(Http.dealResponse(res, request)); }).then($res).catch(function (e) { e.$request = request; return Promise.reject(e); }).catch($rej); }).catch($rej); return req; } /** * 对应微信/支付宝小程序的 uploadFile * */ }, { key: "uploadFile", value: function uploadFile(options) { var _this5 = this; var _this$calcConfig3 = this.calcConfig(options), conf = _this$calcConfig3.config, abort = _this$calcConfig3.abort; var $res; var $rej; var req = new RequestPromise(function (res, rej) { $res = res; $rej = rej; }); req.abort = abort; conf.then(function (config) { var request = _this5.getUploadInstance(config); req.abort = function () { request.abort(); request.aborted = true; }; request.open().then(function (res) { return _this5.checkStatus(Http.dealResponse(res, request)); }).then($res).catch(function (e) { e.$request = request; return Promise.reject(e); }).catch($rej); }).catch($rej); return req; } }, { key: "get", value: function get(url, data, options) { return this.request(url, data, _objectSpread2(_objectSpread2({}, options), {}, { method: 'get' })); } }, { key: "post", value: function post(url, data, options) { return this.request(url, data, _objectSpread2(_objectSpread2({}, options), {}, { method: 'post' })); } }, { key: "put", value: function put(url, data, options) { return this.request(url, data, _objectSpread2(_objectSpread2({}, options), {}, { method: 'put' })); } }, { key: "delete", value: function _delete(url, data, options) { return this.request(url, data, _objectSpread2(_objectSpread2({}, options), {}, { method: 'delete' })); } }], [{ key: "createError", value: function createError(object, request, msg) { // eslint-disable-next-line no-shadow function RequestError() {} var message = getMsg(object); if (!message) { message = getMsg(object.data, msg || (request && request.aborted ? 'Request aborted' : 'Network request error: unknown message!')); } RequestError.prototype = new Error(message); // @ts-ignore var obj = new RequestError(); if (_typeof(object) === 'object') { Object.keys(object).forEach(function (k) { obj[k] = object[k]; }); } if (request) obj.$request = request; return obj; } }, { key: "dealResponse", value: function dealResponse(result, request) { if (_typeof(result) === 'object' && result !== null) { result.$request = request; } return result; } }]); return Http; }(); export default Http; export { EngineName, Http, RequestPromise };