2017-01-25 15:52:22 +00:00
|
|
|
/**
|
|
|
|
* Network functions
|
|
|
|
*
|
|
|
|
* @author Pierre HUBERT
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
2017-02-21 11:37:26 +00:00
|
|
|
ComunicWeb.common.network = {
|
2017-01-25 15:52:22 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @var {object} Cache contener
|
|
|
|
*/
|
|
|
|
cache: {},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Make a GET request
|
|
|
|
*
|
|
|
|
* @param {String} url Destination URL
|
2017-02-21 11:37:26 +00:00
|
|
|
* @param {Boolean} cacheResponse Specify if data can be cached or not (optimize network)
|
2017-01-25 15:52:22 +00:00
|
|
|
* @param {function} GETnextAction What to do next
|
|
|
|
* @return {Boolean} False if it fails
|
|
|
|
*/
|
2017-02-21 11:37:26 +00:00
|
|
|
getRequest: function(url, cacheResponse, GETnextAction){
|
2017-01-25 15:52:22 +00:00
|
|
|
//First, check if it is required to cache the request
|
2017-02-21 11:37:26 +00:00
|
|
|
if(cacheResponse){
|
2017-01-25 15:52:22 +00:00
|
|
|
//Prepare cache entry name
|
|
|
|
var cacheEntryName = encodeURIComponent(url);
|
|
|
|
|
|
|
|
//Check if entry exists
|
|
|
|
if(this.cache[cacheEntryName]){
|
|
|
|
//Call next action with the url contained into the cache
|
|
|
|
GETnextAction(this.cache[cacheEntryName]);
|
|
|
|
|
|
|
|
//Quit function
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
//No cache entry where found or cache is disabled, continue
|
|
|
|
var xhrRequest = new XMLHttpRequest();
|
|
|
|
xhrRequest.open("GET", url);
|
|
|
|
|
|
|
|
xhrRequest.onreadystatechange = function(){
|
|
|
|
if(xhrRequest.readyState == 4){
|
|
|
|
//We check if it is an error
|
|
|
|
if(xhrRequest.status != 200){
|
|
|
|
//It's an error, we will quit soon, but debug message before
|
|
|
|
ComunicWeb.debug.logMessage("GET request failed on " + url + " Got response code " + xhrRequest.status);
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
//Check if it is required to cache result
|
2017-02-21 11:37:26 +00:00
|
|
|
if(cacheResponse){
|
|
|
|
ComunicWeb.common.network.cache[cacheEntryName] = xhrRequest.responseText;
|
2017-01-25 15:52:22 +00:00
|
|
|
}
|
|
|
|
|
2017-02-21 11:37:26 +00:00
|
|
|
ComunicWeb.debug.logMessage("GET request: " + url + " Success (" + xhrRequest.status + ")");
|
|
|
|
|
2017-01-25 15:52:22 +00:00
|
|
|
//Call next action
|
|
|
|
GETnextAction(xhrRequest.responseText);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
//Perform request
|
|
|
|
xhrRequest.send(null);
|
|
|
|
},
|
|
|
|
};
|