turbocommons-ts
Version:
General purpose library that implements frequently used and generic software development tasks
1 lines • 10.1 kB
JavaScript
;Object.defineProperty(exports,"__esModule",{value:!0}),exports.HTTPManager=void 0;var StringUtils_1=require("../utils/StringUtils"),ObjectUtils_1=require("../utils/ObjectUtils"),ArrayUtils_1=require("../utils/ArrayUtils"),HashMapObject_1=require("../model/HashMapObject"),HTTPManagerGetRequest_1=require("./httpmanager/HTTPManagerGetRequest"),HTTPManagerBaseRequest_1=require("./httpmanager/HTTPManagerBaseRequest"),HTTPManager=function(){function t(t){if(void 0===t&&(t=!0),this.baseUrl="",this.asynchronous=!0,this.timeout=0,this.isOnlyHttps=!0,this.internetCheckLocations=["https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js","https://ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.8.3.js","https://code.jquery.com/jquery-3.2.1.slim.min.js"],this._queues=[],this._globalPostParams={},"boolean"!=typeof t)throw new Error("asynchronous is not boolean");this.asynchronous=t}return t.prototype.setGlobalPostParam=function(t,e){if(StringUtils_1.StringUtils.isEmpty(t)||StringUtils_1.StringUtils.isEmpty(e))throw new Error("parameterName and value must be non empty strings");this._globalPostParams[t]=e},t.prototype.isGlobalPostParam=function(t){if(StringUtils_1.StringUtils.isEmpty(t))throw new Error("parameterName must be a non empty string");return Object.keys(this._globalPostParams).indexOf(t)>=0},t.prototype.getGlobalPostParam=function(t){if(!this.isGlobalPostParam(t))throw new Error("parameterName does not exist: "+t);return this._globalPostParams[t]},t.prototype.deleteGlobalPostParam=function(t){""!==this.getGlobalPostParam(t)&&delete this._globalPostParams[t]},t.prototype.createQueue=function(t){if(StringUtils_1.StringUtils.isEmpty(t))throw new Error("name must be a non empty string");for(var e=0,r=this._queues;e<r.length;e++){if(r[e].name===t)throw new Error("queue "+t+" already exists")}this._queues.push({name:t,isRunning:!1,pendingRequests:[]})},t.prototype.countQueues=function(){return this._queues.length},t.prototype.isQueueRunning=function(t){if(StringUtils_1.StringUtils.isEmpty(t))throw new Error("name must be a non empty string");for(var e=0,r=this._queues;e<r.length;e++){var n=r[e];if(n.name===t)return n.isRunning}throw new Error("queue "+t+" does not exist")},t.prototype.deleteQueue=function(t){if(StringUtils_1.StringUtils.isEmpty(t))throw new Error("name must be a non empty string");for(var e=0;e<this._queues.length;e++)if(this._queues[e].name===t){if(this._queues[e].isRunning)throw new Error("queue "+t+" is currently running");return void this._queues.splice(e,1)}throw new Error("queue "+t+" does not exist")},t.prototype.generateUrlQueryString=function(t){var e="",r=[],n=[];if(ObjectUtils_1.ObjectUtils.isObject(t)&&ObjectUtils_1.ObjectUtils.getKeys(t).length>0){if(t instanceof HashMapObject_1.HashMapObject)r=t.getKeys(),n=t.getValues();else{r=Object.getOwnPropertyNames(t);for(var s=0;s<r.length;s++)n.push(t[r[s]])}for(s=0;s<r.length;s++)e+="&"+encodeURIComponent(r[s])+"="+encodeURIComponent(StringUtils_1.StringUtils.isString(n[s])?n[s]:JSON.stringify(n[s]));return e.substring(1,e.length)}throw new Error("keyValuePairs must be a HashMapObject or a non empty Object")},t.prototype.isInternetAvailable=function(t,e){var r=this;if("function"!=typeof t||"function"!=typeof e)throw new Error("params must be functions");if(this.internetCheckLocations.length<=0)throw new Error("no check locations specified");var n=function(s){if(s.length<=0)return e();var i=s.shift();if(!StringUtils_1.StringUtils.isUrl(i))throw new Error("invalid check url : "+i);r.urlExists(String(i+"?r="+StringUtils_1.StringUtils.generateRandom(15,15)),t,function(){return n(s)})};!1===navigator.onLine?e():n(this.internetCheckLocations.slice(0))},t.prototype.urlExists=function(t,e,r){if(!StringUtils_1.StringUtils.isString(t))throw new Error("url must be a string");if("function"!=typeof e||"function"!=typeof r)throw new Error("params must be functions");var n=this._composeUrl(this.baseUrl,t);if(StringUtils_1.StringUtils.isUrl(n)){var s=new HTTPManagerGetRequest_1.HTTPManagerGetRequest(n);s.successCallback=function(){return e()},s.errorCallback=function(){return r()},this.execute(s)}else r()},t.prototype.getUrlHeaders=function(e,r,n){var s=this,i=this._composeUrl(this.baseUrl,e);if(!StringUtils_1.StringUtils.isString(i))throw new Error("url must be a string");if("function"!=typeof r||"function"!=typeof n)throw new Error("params must be functions");if(!StringUtils_1.StringUtils.isUrl(i))throw new Error("invalid url "+i);var o=new XMLHttpRequest;this.timeout>0&&(o.timeout=this.timeout),o.open("GET",i,this.asynchronous),o.onload=function(){return r(o.getAllResponseHeaders().split("\n"))},o.onerror=function(){return n(o.statusText,o.status)},o.ontimeout=function(){return n(s.timeout+t.ERROR_TIMEOUT,408)},this._executeXmlHttprequestSend(o,i)},t.prototype.execute=function(e,r,n){var s=this;void 0===r&&(r=null),void 0===n&&(n=null);var i=this._generateValidRequestsList(e);if(null!==r&&!(r instanceof Function)||null!==n&&!(n instanceof Function))throw new Error("finishedCallback and progressCallback must be functions");for(var o=0,a=!1,u=[],l=function(t,e,l,g,p){var c=t.request,h=s._composeUrl(s.baseUrl,c.url),f=e;if(c.resultFormat===HTTPManagerBaseRequest_1.HTTPManagerBaseRequest.JSON)try{f=JSON.parse(e)}catch(t){l||(l=!0,g="Could not parse request result as a json string")}o++,u[t.index]={url:h,response:f,isError:l,errorMsg:g,code:p},l?(a=!0,c.errorCallback(g,p,e)):c.successCallback(f),c.finallyCallback(),null!==n&&n(h,i.length),o>=i.length&&null!==r&&r(u,a)},g=function(e){var r,n={index:e,request:i[e]};if(!StringUtils_1.StringUtils.isString(i[e].url)||StringUtils_1.StringUtils.isEmpty(i[e].url))throw new Error("url "+e+" must be a non empty string");try{r=new XMLHttpRequest}catch(t){throw new Error("Could not initialize XMLHttpRequest. If running node, it is not natively available. We recommend npm xhr2 library that emulates XMLHttpRequest on node apps (global.XMLHttpRequest = require('xhr2'))")}(i[e].timeout>0||p.timeout>0)&&(r.timeout=i[e].timeout>0?i[e].timeout:p.timeout);var o=p._composeUrl(p.baseUrl,i[e].url),a=i[e]instanceof HTTPManagerGetRequest_1.HTTPManagerGetRequest?"GET":"POST";if(r.open(a,o,p.asynchronous),r.onload=function(){r.status>=200&&r.status<400?l(n,r.responseText,!1,"",r.status):l(n,r.responseText,!0,r.statusText,r.status)},r.onerror=function(){l(n,r.responseText,!0,r.statusText,r.status)},r.ontimeout=function(){l(n,r.responseText,!0,s.timeout+t.ERROR_TIMEOUT,408)},"GET"===a&&p._executeXmlHttprequestSend(r,o),"POST"===a||Object.keys(p._globalPostParams).length>0)try{var u="POST"===a?i[e].parameters:{};if(!1===i[e].ignoreGlobalPostParams)for(var g=0,c=Object.keys(p._globalPostParams);g<c.length;g++){var h=c[g];u instanceof HashMapObject_1.HashMapObject?u.set(h,p._globalPostParams[h]):u[h]=p._globalPostParams[h]}r.setRequestHeader("Content-type","application/x-www-form-urlencoded"),r.send(p.generateUrlQueryString(u))}catch(t){p._executeXmlHttprequestSend(r,o)}},p=this,c=0;c<i.length;c++)g(c)},t.prototype._executeXmlHttprequestSend=function(t,e){try{t.send()}catch(t){throw new Error("HTTPManager could not execute request to "+e+"\n"+t.toString())}},t.prototype._generateValidRequestsList=function(t){var e=[];if(ArrayUtils_1.ArrayUtils.isArray(t)){if(t.length<=0)throw new Error("No requests to execute");for(var r=0,n=t;r<n.length;r++){var s=n[r];StringUtils_1.StringUtils.isString(s)?e.push(new HTTPManagerGetRequest_1.HTTPManagerGetRequest(s)):e.push(s)}}else if(StringUtils_1.StringUtils.isString(t)&&!StringUtils_1.StringUtils.isEmpty(t))e=[new HTTPManagerGetRequest_1.HTTPManagerGetRequest(t)];else{if(!(t instanceof HTTPManagerBaseRequest_1.HTTPManagerBaseRequest))throw new Error("Invalid requests value");e=[t]}return e},t.prototype.queue=function(t,e,r){void 0===r&&(r=null);var n=this._generateValidRequestsList(t);if(null!==r&&!(r instanceof Function))throw new Error("finishedCallback and progressCallback must be functions");for(var s=0,i=this._queues;s<i.length;s++){var o=i[s];if(o.name===e){for(var a=0;a<n.length;a++)o.pendingRequests.unshift(n[a]);if(null!==r){var u=new HTTPManagerGetRequest_1.HTTPManagerGetRequest("FINISHED_REQUEST_CALLBACK");u.finallyCallback=r,o.pendingRequests.unshift(u)}return void(this.isQueueRunning(e)||this._startQueue(e))}}throw new Error("queue "+e+" does not exist. Create it with createQueue()")},t.prototype._startQueue=function(t){for(var e=this,r=function(t){if(t.pendingRequests.length<=0)t.isRunning=!1;else{if("FINISHED_REQUEST_CALLBACK"===t.pendingRequests[t.pendingRequests.length-1].url){var n=t.pendingRequests.pop();t.pendingRequests.length<=0&&(t.isRunning=!1),n.finallyCallback()}t.pendingRequests.length>0&&(t.isRunning=!0,e.execute(t.pendingRequests.pop(),function(){return r(t)}))}},n=0,s=this._queues;n<s.length;n++){var i=s[n];if(i.name===t)return void r(i)}},t.prototype.loadResourcesFromList=function(t,e,r,n,s){var i=this;if(void 0===s&&(s=null),!StringUtils_1.StringUtils.isString(t)||StringUtils_1.StringUtils.isEmpty(t))throw new Error("urlToListOfResources must be a non empty string");if(!StringUtils_1.StringUtils.isString(e)||StringUtils_1.StringUtils.isEmpty(e))throw new Error("baseUrl must be a non empty string");this.execute(t,function(o,a){if(o[0].isError)return n(t,o[0].errorMsg,o[0].code);for(var u=[],l=StringUtils_1.StringUtils.getLines(o[0].response),g=0,p=l;g<p.length;g++){var c=p[g];u.push(StringUtils_1.StringUtils.formatPath(i._composeUrl(e,c),"/"))}i.execute(u,function(t,e){for(var s=[],i=0,o=t;i<o.length;i++){var a=o[i];if(a.isError)return n(a.url,a.errorMsg,a.code);s.push(a.response)}r(l,s)},s)})},t.prototype._composeUrl=function(t,e){var r="";if(r=StringUtils_1.StringUtils.isEmpty(t)||"http:"===e.substr(0,5)||"https:"===e.substr(0,6)?e:StringUtils_1.StringUtils.replace(StringUtils_1.StringUtils.formatPath(t+"/"+e,"/"),["http:/","https:/"],["http://","https://"],1),this.isOnlyHttps&&"http:"===r.substr(0,5).toLowerCase())throw new Error("Non secure http requests are forbidden. Set isOnlyHttps=false to allow "+r);return r},t.ERROR_TIMEOUT=" ms Timeout reached",t}();exports.HTTPManager=HTTPManager;