x-http-client
Version:
An http client to make it easier to send requests (including JSONP requests) to the server.
87 lines (75 loc) • 2.43 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_CANCELLED = constants.ERR_CANCELLED;
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 || 0, 10);
var timeoutId = null;
/**
* 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_CANCELLED);
};
// Add timeout listener
if (!isNaN(timeout) && timeout > 0) {
timeoutId = setTimeout(function () {
finish(ERR_TIMEOUT);
}, timeout);
}
}
module.exports = addEventListeners;