util-helpers
Version:
58 lines (54 loc) • 2.41 kB
JavaScript
;
var native = require('./utils/native.js');
function ajax(url, options) {
var _a = options || {}, _b = _a.method, method = _b === void 0 ? 'get' : _b, _c = _a.data, data = _c === void 0 ? null : _c, timeout = _a.timeout, headers = _a.headers, _d = _a.withCredentials, withCredentials = _d === void 0 ? false : _d, _e = _a.async, async = _e === void 0 ? true : _e, _f = _a.user, user = _f === void 0 ? null : _f, _g = _a.password, password = _g === void 0 ? null : _g, responseType = _a.responseType, onReadyStateChange = _a.onReadyStateChange, onLoadStart = _a.onLoadStart, onProgress = _a.onProgress, onAbort = _a.onAbort, onTimeout = _a.onTimeout, onError = _a.onError, onLoad = _a.onLoad, onLoadEnd = _a.onLoadEnd;
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method.toLowerCase(), url, async, user, password);
if (onReadyStateChange) {
xhr.onreadystatechange = onReadyStateChange;
}
if (typeof timeout === 'number' && timeout > 0) {
xhr.timeout = timeout;
}
xhr.withCredentials = withCredentials;
if (responseType) {
xhr.responseType = responseType;
}
if (typeof headers === 'object') {
native.objectKeys(headers).map(function (item) {
xhr.setRequestHeader(item, headers[item]);
});
}
var wrapSuccess = function (cb) {
return function (e) {
resolve(e);
cb === null || cb === void 0 ? void 0 : cb.call(xhr, e);
};
};
var wrapError = function (cb) {
return function (e) {
reject(e);
cb === null || cb === void 0 ? void 0 : cb.call(xhr, e);
};
};
var events = {
loadstart: onLoadStart,
progress: onProgress,
abort: wrapError(onAbort),
timeout: wrapError(onTimeout),
error: wrapError(onError),
load: wrapSuccess(onLoad),
loadend: onLoadEnd
};
var eventKeys = native.objectKeys(events);
eventKeys.forEach(function (item) {
var func = events[item];
if (func) {
xhr.addEventListener(item, func);
}
});
xhr.send(data);
});
}
module.exports = ajax;