Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- apiRequest : function(requestURL, requestHandler){
- /*Sends an AJAX request to the specified requestURL and uses the requestHandler to respond
- *The requestHandler recieves the api request in a json as a parameter and may be used as such
- *All API requests use GET requests
- */
- if(this.supports_storage()){
- var apiUrl = requestURL.removeParams();
- if(typeof this.cachedURL(apiUrl) == "undefined" || !this.cachedURL(apiUrl)){
- console.log("fetching data");
- var xmlHttp = null;
- xmlHttp = new XMLHttpRequest();
- xmlHttp.onreadystatechange = function(){
- //Call the handler
- if(typeof xmlHttp.responseText != "undefined"){
- if(xmlHttp.readyState==4 && xmlHttp.status==200){
- var result = JSON.parse(xmlHttp.responseText);
- console.log(typeof this);
- requestHandler(result);
- //Add resulting json from api to local storage
- localStorage.setItem(apiUrl,JSON.stringify(result))
- //Mark as cached
- if(typeof fins.cachedURLs == "undefined"){
- fins.cachedURLs = {};
- }
- fins.cachedURLs[apiUrl] = true;
- }
- }
- };
- xmlHttp.open( "GET", requestURL, true );
- xmlHttp.send( null );
- }else{
- //The result is cached so we should go ahead and give that to the function
- console.log("using cache");
- requestHandler(JSON.parse(localStorage.getItem(apiUrl))) ;
- }
- }else{
- throw new Error("Local browser storage no supported, use more modern browser");
- }
- },
- apiSendData : function(sendURL,requestHandler){
- var xmlHttp = null;
- xmlHttp = new XMLHttpRequest();
- xmlHttp.onreadystatechange = function(){
- //Convert the response to JSON first.
- if(typeof xmlHttp.responseText != "undefined"){
- requestHandler(JSON.parse(xmlHttp.responseText));
- }
- };
- xmlHttp.open( "GET", sendURL, true );
- xmlHttp.send( null );
- //Mark the url that maps to retrieving this data
- if(typeof apiURLMaps[sendURL] == "undefined"){
- throw new Error("Invalid API request in fins:apiSendData, no mapping exists");
- }
- //Mark the corresponding retrievel request for the sending action as dirty and in need of being recached
- cachedURLs[apiURLMaps[sendURL]] = false;
- },
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement