x-http-client
Version:
An http client to simplify sending requests (HTTP & JSONP) in the browser.
91 lines (78 loc) • 2.51 kB
JavaScript
var isFunction = require('x-common-utils/isFunction');
var JSONPResponse = require('../class/JSONPResponse');
var fireCallbacks = require('../shared/fireCallbacks');
var noop = require('../shared/noop');
var constants = require('../shared/constants');
var ERR_CANCELED = constants.ERR_CANCELED;
var ERR_NETWORK = constants.ERR_NETWORK;
var ERR_RESPONSE = constants.ERR_RESPONSE;
var ERR_TIMEOUT = constants.ERR_TIMEOUT;
/**
* Add event listeners to JSONP request.
*
* @param {JSONPRequest} request The JSONP request.
* @param {string} callbackName The callback name used to define the global JSONP callback.
*/
function addEventListeners(request, callbackName) {
var script = request.script;
var options = request.options;
var requestType = request.requestType;
var isResponseOk = options.isResponseOk;
var response = new JSONPResponse(request);
var timeout = parseInt(options.timeout, 10) || 0;
var timeoutId = null;
if (timeout <= 0) {
timeout = parseInt(options.jsonpDefaultTimeout, 10) || 0;
}
/**
* The function finish the request.
*
* @param {string} code The error code on error. If no error occured, the code is `null`.
*/
var finish = function (code) {
// Set finish to the no operation function.
finish = noop;
// Mark this request as finished.
request.finished = true;
// Clear listeners.
window[callbackName] = noop;
script.onerror = null;
// Clear timeout.
if (timeoutId !== null) {
clearTimeout(timeoutId);
timeoutId = null;
}
// Fire callbacks.
fireCallbacks(code, response);
};
// Define the callback function.
window[callbackName] = function (responseJSON) {
request.responseJSON = responseJSON;
if (isFunction(isResponseOk)) {
if (isResponseOk(requestType, response)) {
finish(null);
} else {
finish(ERR_RESPONSE);
}
} else {
finish(null);
}
};
// Catch the error.
script.onerror = function () {
finish(ERR_NETWORK);
};
/**
* Cancel the request.
*/
request.cancel = function () {
finish(ERR_CANCELED);
};
// Add timeout listener
if (timeout > 0) {
timeoutId = setTimeout(function () {
finish(ERR_TIMEOUT);
}, timeout);
}
}
module.exports = addEventListeners;