UNPKG

wiz-frameworks

Version:

wizlong react framework

437 lines (361 loc) 13 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.REQUEST_METHODS = undefined; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _utils = require('./utils'); var _error = require('./error'); var _error2 = _interopRequireDefault(_error); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var REQUEST_METHODS = exports.REQUEST_METHODS = ['GET', 'POST', 'HEAD', 'DELETE', 'OPTIONS', 'PUT', 'PATCH']; var Request = function () { function Request() { var _this = this; var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Request); _initialiseProps.call(this); this._options = _extends({}, this.defaultOptions, opts); // normalize the headers var headers = this._options.headers; for (var h in headers) { if (h !== h.toLowerCase()) { headers[h.toLowerCase()] = headers[h]; delete headers[h]; } } REQUEST_METHODS.forEach(function (method) { _this[method.toLowerCase()] = function (url, data) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; options.data = data; return _this.send(url, _extends({}, options, { method: method })); }; }); } /** * default options */ /** * Set Options * * Examples: * * .config('method', 'GET') * .config({headers: {'content-type': 'application/json'}}) * * @param {String|Object} key * @param {Any} value * @return {Request} */ /** * Set headers * * Examples: * * .headers('Accept', 'application/json') * .headers({ Accept: 'application/json' }) * * @param {String|Object} key * @param {String} value * @return {Request} */ /** * Set Content-Type * * @param {String} type */ /** * GET send form */ /** * POST send form */ // send request _createClass(Request, [{ key: '__checkStatus', value: function __checkStatus(response) { if (response.status >= 200 && response.status < 300 || response.status === 400 || response.status === 401) { if (response.status === 204) { return null; } if (response.status === 401) { rotueHistory.push('/sign/login'); } return response; } var errortext = response.statusText; var error = new _error2['default'](errortext, response.status); error.response = response; throw error; } }, { key: '__parseResponse', value: function __parseResponse(response, responseType) { return (0, _utils.isFunction)(response && response[responseType]) ? response[responseType]() : response; } }, { key: '__afterResponse', value: function __afterResponse(response, afterResponse, info) { if ((0, _utils.isFunction)(afterResponse)) { var after = afterResponse(response, info); return after; } return response; } }, { key: '__errorHandle', value: function __errorHandle(e, errorHandle, reject, info) { if (e.name !== 'RequestError') { e.name = 'RequestError'; e.code = 0; } if (!(0, _utils.isFunction)(errorHandle) || errorHandle(e, info) !== false) { reject(e); } } }, { key: '__timeoutFetch', value: function __timeoutFetch(url, fetchOpts, options) { var timeout = options.timeout; if (timeout && typeof timeout === 'number') { return Promise.race([fetch(url, fetchOpts), new Promise(function (resolve, reject) { return setTimeout(function () { return reject(new _error2['default']('request timeout of ' + timeout + ' ms.', 'timeout')); }, timeout); })]); } else { return fetch(url, fetchOpts); } } }]); return Request; }(); var _initialiseProps = function _initialiseProps() { var _this2 = this; this.defaultOptions = { method: 'POST', // default mode: 'cors', cache: 'no-cache', credentials: 'include', headers: { 'content-type': 'application/json' }, responseType: 'json', // text or blob or formData https://fetch.spec.whatwg.org/ prefix: '', // request prefix beforeRequest: null, // before request check, return false or a rejected Promise will stop request afterResponse: null, // after request hook errorHandle: null, // global error handle withHeaders: null, // function & object, every request will take it timeout: null // request timeout }; this.create = function (opts) { return new Request(opts); }; this.config = function (key, value) { var options = _this2._options; if (typeof key === 'object') { for (var k in key) { options[k] = key[k]; } } else { options[key] = value; } return _this2; }; this.prefix = function (prefix) { if (prefix && typeof prefix === 'string') _this2._options.prefix = prefix; return _this2; }; this.timeout = function (timeout) { if (timeout && typeof timeout === 'number') _this2._options.timeout = timeout; return _this2; }; this.beforeRequest = function (cb) { var options = _this2._options; if ((0, _utils.isFunction)(cb)) { options.beforeRequest = cb; } return _this2; }; this.afterResponse = function (cb) { var options = _this2._options; if ((0, _utils.isFunction)(cb)) { options.afterResponse = cb; } return _this2; }; this.errorHandle = function (cb) { var options = _this2._options; if ((0, _utils.isFunction)(cb)) { options.errorHandle = cb; } return _this2; }; this.withHeaders = function (cb) { var options = _this2._options; if ((0, _utils.isFunction)(cb)) { options.withHeaders = cb; } return _this2; }; this.headers = function (key, value) { var headers = _this2._options.headers; if ((0, _utils.isObject)(key)) { for (var k in key) { headers[k.toLowerCase()] = key[k]; } } else if ((0, _utils.isFunction)(key)) { headers.__headersFun__ = key; } else { headers[key.toLowerCase()] = value; } return _this2; }; this.contentType = function (type) { var headers = _this2._options.headers; switch (type) { case 'json': type = 'application/json'; break; case 'form': case 'urlencoded': type = 'application/x-www-form-urlencoded;charset=UTF-8'; break; case 'multipart': type = 'multipart/form-data'; break; } headers['content-type'] = type; return _this2; }; this.getform = function (url, data) { var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; opts.data = data; return _this2.send(url, _extends({}, opts, { method: 'GET', headers: _extends({}, _this2._options.headers, opts.headers, { 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8' }) })); }; this.postform = function (url, data) { var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; opts.data = data; return _this2.send(url, _extends({}, opts, { method: 'POST', headers: _extends({}, _this2._options.headers, opts.headers, { 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8' }) })); }; this.send = function (url) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return new Promise(function (resolve, reject) { if (typeof url !== 'string') { return reject(new _error2['default']('invalid url', 'invalidURL')); } var data = opts.data, otherOpts = _objectWithoutProperties(opts, ['data']); var options = _extends({}, _this2._options, otherOpts); var beforeRequest = options.beforeRequest, afterResponse = options.afterResponse, errorHandle = options.errorHandle, responseType = options.responseType, prefix = options.prefix, headers = options.headers, withHeaders = options.withHeaders, timeout = options.timeout, fetchOpts = _objectWithoutProperties(options, ['beforeRequest', 'afterResponse', 'errorHandle', 'responseType', 'prefix', 'headers', 'withHeaders', 'timeout']); /******************* * format header *******************/ var __headersFun__ = headers.__headersFun__, realheaders = _objectWithoutProperties(headers, ['__headersFun__']); var newheaders = _extends({}, realheaders); if ((0, _utils.isFunction)(withHeaders)) { var _newheaders = withHeaders(); if (_newheaders && (0, _utils.isObject)(_newheaders)) { newheaders = _extends({}, newheaders, _newheaders); } } else if ((0, _utils.isObject)(withHeaders)) { newheaders = _extends({}, newheaders, withHeaders); } if (__headersFun__) { var _newheaders2 = __headersFun__(); if (_newheaders2 && (0, _utils.isObject)(_newheaders2)) { newheaders = _extends({}, newheaders, _newheaders2); } } fetchOpts.headers = newheaders; /*********************** * format data to body ***********************/ var contentType = newheaders['content-type']; fetchOpts.body = data; // if FormData if (contentType.indexOf('multipart/form-data') !== -1 || data instanceof FormData) { if (data instanceof FormData) { fetchOpts.body = data; } else if ((0, _utils.isObject)(data)) { fetchOpts.body = new FormData(); for (var k in data) { fetchOpts.body.append(k, data[k]); } } // If it is FormData, content-type: 'multipart/form-data' is deleted, // otherwise the boundary will not be added automatically delete fetchOpts.headers['content-type']; } // if json else if (contentType.indexOf('application/json') !== -1) { fetchOpts.body = JSON.stringify(fetchOpts.body); } // if form else if (contentType.indexOf('application/x-www-form-urlencoded') !== -1) { fetchOpts.body = (0, _utils.param)(fetchOpts.body); } // if 'GET' request, join _body of url queryString if (fetchOpts.method.toUpperCase() === 'GET' && data) { if (url.indexOf('?') >= 0) { url += '&' + (0, _utils.param)(data); } else { url += '?' + (0, _utils.param)(data); } delete fetchOpts.body; } /******************* * format url *******************/ var nextURL = void 0; if (/^(http|https|ftp)\:\/\//.test(url)) { nextURL = url; } else { nextURL = prefix + url; } if ((0, _utils.isFunction)(beforeRequest) && beforeRequest(nextURL, fetchOpts) === false) { return reject(new _error2['default']('request canceled by beforeRequest', 'requestCanceled')); } return _this2.__timeoutFetch(nextURL, fetchOpts, options).then(function (resp) { return _this2.__checkStatus(resp); }).then(function (resp) { return _this2.__parseResponse(resp, responseType); }).then(function (resp) { return _this2.__afterResponse(resp, afterResponse, _extends({ prefix: prefix, url: url }, fetchOpts)); }).then(function (response) { return resolve(response); })['catch'](function (e) { return _this2.__errorHandle(e, errorHandle, reject, _extends({ prefix: prefix, url: url }, fetchOpts)); }); }); }; }; exports['default'] = Request;