jsql-angular1
Version:
JSQL plugin for Angular 1.6
1 lines • 10.9 kB
JavaScript
"use strict";if(window.JSQL)throw new Error("JSQL: Main object conflict");window.JSQL=function(config){this.__version="2.1.0",this.host=null,this.path=null,this.querySet={},this.headers={Accept:"application/json","Content-Type":"application/json"},config&&(config.apiKey&&(this.headers["Api-Key"]=config.apiKey),config.devKey&&(this.headers["Dev-Key"]=config.devKey)),this.hideErrors=!1,this.rxjs=!1,this.setConfig(config)},JSQL.prototype.version=function(){console.warn("JSQL version: "+this.__version)},JSQL.prototype.setConfig=function(config){null!=config&&0!==Object.keys(config).length||(config={}),void 0!==config.host&&null!==config.host&&"string"==typeof config.host&&0!==config.host.trim().length&&""!==config.host||(config.host="https://provider.jsql.it/"),void 0!==config.path&&null!==config.path&&"string"==typeof config.path&&0!==config.path.trim().length&&""!==config.path||(config.path="/api/jsql/"),config.host.endsWith("/")&&config.path.startsWith("/")&&(config.path=config.path.substring(1,config.path.length)),config.host.endsWith("/")||config.path.startsWith("/")||(config.path="/"+config.path),config.path.endsWith("/")||(config.path+="/"),void 0!==config.hideErrors&&null!==config.hideErrors&&(this.hideErrors=config.hideErrors),this.host=config.host,this.path=config.path,this.url=this.host+this.path,this.rxjs=void 0!==config.rxjs&&config.rxjs},JSQL.prototype.request=function(){this.throw("No request implementation")},JSQL.prototype.wrap=function(){this.throw("No wrap implementation")},JSQL.prototype.construct=function(token,type,options){var _JSQL=this;null!=token&&(this.isArray(token)||token.__isStructure&&(token=token.build()));var isTransaction=!1;function prepareForTransaction(){isTransaction=!0,options||(options={headers:{}}),void 0!==options.headers&&null!==options.headers||(options.headers={}),options.headers.txid=token.txid,token=token.token}"rollback"===type||"commit"===type?prepareForTransaction():null!=token&&token.token&&token.txid&&prepareForTransaction(),isTransaction&&"rollback"!==type&&"commit"!==type&&void 0===token||null===token||"string"!=typeof token&&!this.isArray(token)?this.throw("Unable to execute with unset token"):null!=token&&("string"==typeof token||this.isArray(token))||this.throw("Unable to execute with unset token");var defaultOptions={throwSelectOneError:!1,ignoreSelectOneMoreResults:"selectOne"===type,headers:{},successName:"success",errorName:"error",alwaysName:"always"};if(null==options)options=defaultOptions;else for(var option in defaultOptions)defaultOptions.hasOwnProperty(option)&&(void 0!==options[option]&&null!==options[option]||(options[option]=defaultOptions[option]));for(var header in void 0!==options.headers&&null!==options.headers||(options.headers={}),_JSQL.headers)_JSQL.headers.hasOwnProperty(header)&&(void 0!==options.headers[header]&&null!==options.headers[header]||(options.headers[header]=_JSQL.headers[header]));token=this.removePrefix(token);var promise={xhrPromise:null,type:type,isUsedParamsArray:!1,isTransaction:isTransaction,headers:options.headers,options:options,data:{token:token,params:{}},querySet:[],catchCallback:function(){},param:function(paramName,paramValue){return"rollback"===promise.type?_JSQL.throw("Transactions already rollbacked"):"commit"===promise.type?_JSQL.throw("Transaction already commited"):promise.isUsedParamsArray?_JSQL.throw("Cannot mix params array and single params"):null!=paramName&&"string"==typeof paramName&¶mValue?(void 0!==promise.data.params[paramName]&&console.warn('JSQL: Parameter "'+paramName+'" already exist, will be replaced'),promise.data.params[paramName]=paramValue):_JSQL.throw('"param" function accept args: [paramName:string, paramValue:primitive]'),promise},params:function(paramsArrayOrParamsObject){if("rollback"===promise.type)return _JSQL.throw("Transactions already rollbacked"),promise;if("commit"===promise.type)return _JSQL.throw("Transaction already commited"),promise;if(_JSQL.isArray(paramsArrayOrParamsObject)){if(!_JSQL.isEmptyObject(promise.data.params))return _JSQL.throw("Cannot mix params array and object params"),promise;promise.isUsedParamsArray=!0,promise.data.params=paramsArrayOrParamsObject}else _JSQL.each(paramsArrayOrParamsObject,function(paramName,paramValue){promise.data.params[paramName]&&console.warn('JSQL: Parameter "'+paramName+'" already exist, will be replaced'),promise.data.params[paramName]=paramValue});return promise},successResultCallback:function(result,callBack){if("commit"===promise.type||"rollback"===promise.type){if(_JSQL.rxjs)return result;callBack(result)}else if("selectOne"===promise.type&&!promise.options.ignoreSelectOneMoreResults&&1<result.length)promise.options.throwSelectOneError=!0;else if(_JSQL.isArray(result)){if(_JSQL.rxjs)return"selectOne"===promise.type&&promise.options.ignoreSelectOneMoreResults?0<result.length?result[0]:null:result;"selectOne"===promise.type&&promise.options.ignoreSelectOneMoreResults?callBack(0<result.length?result[0]:null):callBack(result)}else{if(_JSQL.rxjs)return"selectOne"===promise.type&&promise.options.ignoreSelectOneMoreResults&&null!=(dataProp=_JSQL.getDataProperty(result))&&(result[dataProp]=0<result[dataProp].length?result[dataProp][0]:null),result;var dataProp;"selectOne"===promise.type&&promise.options.ignoreSelectOneMoreResults&&null!=(dataProp=_JSQL.getDataProperty(result))&&(result[dataProp]=0<result[dataProp].length?result[dataProp][0]:null),callBack(result)}},ok:function(){_JSQL.rxjs||promise.then(function(){})},then:function(callBack){return promise.checkAndCreateXhrPromise(),promise.createAlways(),promise.xhrPromise[promise.options.successName](function(result){promise.successResultCallback(result,callBack)}),promise},thenRxjs:function(result){return promise.successResultCallback(result)},catch:function(callBack){return promise.checkAndCreateXhrPromise(),promise.createAlways(),promise.xhrPromise[promise.options.errorName](function(error){callBack(error)}),promise.catchCallback=callBack,promise},catchRxjs:function(error){return error},createAlways:function(){promise.xhrPromise[promise.options.alwaysName]||(promise.xhrPromise[promise.options.alwaysName]=function(){promise.options.throwSelectOneError&&promise.catchCallback("JSQL: More than one result not allowed with selectOne")})},checkAndCreateXhrPromise:function(){promise.xhrPromise||(promise.xhrPromise=_JSQL.request(_JSQL.url+("selectOne"===promise.type?"select":promise.type),promise.data,promise.headers,promise))}};return promise},JSQL.prototype.select=function(token){return this.wrap(token,"select",this)},JSQL.prototype.selectOne=function(token){return this.wrap(token,"selectOne",this)},JSQL.prototype.update=function(token){return this.wrap(token,"update",this)},JSQL.prototype.insert=function(token){return this.wrap(token,"insert",this)},JSQL.prototype.remove=function(token){return this.wrap(token,"delete",this)},JSQL.prototype.delete=function(token){return this.wrap(token,"delete",this)},JSQL.prototype.querySet={},JSQL.prototype.repoSet={},JSQL.prototype.repo=function(name){if(!name)return this.repoSet;var repoSet={};name&&(this.repoSet[name]||(this.repoSet[name]={}),repoSet=this.repoSet[name]);var self=this,repoObj={name:name,set:function(queryName,sqlQueryFunction){return self.set(this.name+"."+queryName,sqlQueryFunction),this},get:function(queryName){var args=self.toArray(arguments);return args.shift(),args.unshift(this.name+"."+queryName),self.get.apply(self,args)}};return Object.assign(repoObj,repoSet)},JSQL.prototype.get=function(queryName){var set=this.querySet[queryName]||null;if(this.isFunction(set)){for(var args=[],i=1;i<arguments.length;i++)args.push(arguments[i]);return set.apply(this,args).build()}return set},JSQL.prototype.set=function(queryName,sqlQuery){return this.querySet[queryName]=sqlQuery,this},JSQL.prototype.query=function(sqlQuery){var self=this,setName="set_"+Object.keys(this.querySet).length;return this.querySet[setName]=[sqlQuery],{__isStructure:!0,__setName:setName,build:function(){return self.querySet[this.__setName]},append:function(sqlQuery){return self.querySet[this.__setName].push(" "+sqlQuery+" "),this}}},JSQL.prototype.txid=function(){for(var text="",possible="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",time=(new Date).getTime()+"",i=0;i<time.length;i++)text+=possible.charAt(Math.floor(Math.random()*possible.length)),text+=time[0];return text},JSQL.prototype.tx=function(){var self=this,jsqlTx={__txid:self.txid(),select:function(token){return self.wrap({token:token,txid:jsqlTx.__txid},"select",self)},selectOne:function(token){return self.wrap({token:token,txid:jsqlTx.__txid},"selectOne",self)},update:function(token){return self.wrap({token:token,txid:jsqlTx.__txid},"update",self)},insert:function(token){return self.wrap({token:token,txid:jsqlTx.__txid},"insert",self)},remove:function(token){return self.wrap({token:token,txid:jsqlTx.__txid},"delete",self)},delete:function(token){return self.wrap({token:token,txid:jsqlTx.__txid},"delete",self)},commit:function(){return self.wrap({token:"",txid:jsqlTx.__txid},"commit",self)},rollback:function(){return self.wrap({token:"",txid:jsqlTx.__txid},"rollback",self)}};return jsqlTx},JSQL.prototype.isFunction=function(obj){return"function"==typeof obj||!1},JSQL.prototype.throw=function(error){if(!this.hideErrors)throw new Error("JSQL Core error: "+error)},JSQL.prototype.each=function(obj,iterator){for(var prop in obj)obj.hasOwnProperty(prop)&&iterator(prop,obj[prop])},JSQL.prototype.isEmptyObject=function(obj){var isEmpty=!0;for(var prop in obj)if(obj.hasOwnProperty(prop)&&void 0!==obj[prop]){isEmpty=!1;break}return isEmpty},JSQL.prototype.isArray=function(obj){return void 0===Array.isArray?"[object Array]"===Object.prototype.toString.call(obj):Array.isArray(obj)},JSQL.prototype.toArray=function(arrayLike){for(var arr=[],i=0;i<arrayLike.length;i++)arr[i]=arrayLike[i];return arr},JSQL.prototype.getDataProperty=function(result){return result.data?"data":result.body?"body":null},JSQL.prototype.removePrefix=function(token){var toRpl={a:"@",b:"sql",c:function(){return this.a+this.b}};if(this.isArray(token)){for(var i=0;i<token.length;i++)token[i]=token[i].replace(toRpl.c(),"").trim();return token}return token.replace(toRpl.c(),"").trim()},void 0!==window.module&&(module.exports=JSQL),function(angular){angular.module("jsql-angular",[]).provider("jsql",function(){var _jsql=null,config=null;this.setConfig=function(jsqlConfig){config=jsqlConfig},this.$get=["$http",function($http){return null==_jsql&&(function($http){JSQL.prototype.request=function(requestUrl,requestData,requestHeaders){return $http({url:requestUrl,method:"POST",dataType:"json",headers:requestHeaders,data:requestData})},JSQL.prototype.wrap=function(token,queryType){return this.construct(token,queryType,{successName:"then",errorName:"catch",alwaysName:"finally"})}}($http),_jsql=new JSQL(config)),_jsql}]})}(angular);