UNPKG

@stratusjs/angularjs

Version:

This is the AngularJS package for StratusJS.

1 lines 17.4 kB
System.register(["lodash","@stratusjs/runtime/stratus","@stratusjs/core/errors/errorBase","@stratusjs/core/misc","@stratusjs/core/datastore/modelBase","@stratusjs/core/environment","@stratusjs/core/datastore/xhr","../injector","./collection","toastify-js"],function(exports_1,context_1){"use strict";var lodash_1,stratus_1,errorBase_1,misc_1,modelBase_1,environment_1,xhr_1,injector_1,collection_1,toastify_js_1,injector,$rootScope,serviceVerify,ModelOptionKeys,Model;context_1&&context_1.id;return{setters:[function(lodash_1_1){lodash_1=lodash_1_1},function(stratus_1_1){stratus_1=stratus_1_1},function(errorBase_1_1){errorBase_1=errorBase_1_1},function(misc_1_1){misc_1=misc_1_1},function(modelBase_1_1){modelBase_1=modelBase_1_1},function(environment_1_1){environment_1=environment_1_1},function(xhr_1_1){xhr_1=xhr_1_1},function(injector_1_1){injector_1=injector_1_1},function(collection_1_1){collection_1=collection_1_1},function(toastify_js_1_1){toastify_js_1=toastify_js_1_1}],execute:function(){injector=injector_1.getInjector(),serviceVerify=async()=>new Promise(async(resolve,_reject)=>{$rootScope?resolve(!0):(injector||(injector=injector_1.getInjector()),injector&&($rootScope=injector.get("$rootScope")),$rootScope?resolve(!0):setTimeout(()=>{environment_1.cookie("env")&&console.log("wait for $rootScope service:",{$rootScope}),serviceVerify().then(resolve)},250))}),exports_1("ModelOptionKeys",ModelOptionKeys=["autoSave","autoSaveInterval","autoSaveHalt","collection","completed","manifest","serviceId","stagger","target","targetSuffix","toast","type","urlRoot","urlSync","watch","withCredentials","payload","convoy","headers","ignoreKeys","received"]),Model=class extends modelBase_1.ModelBase{name="Model";target=null;type=null;manifest=!1;stagger=!1;toast=!0;identifier=null;urlRoot="/Api";targetSuffix=null;serviceId=null;header=new modelBase_1.ModelBase;meta=new modelBase_1.ModelBase;route=new modelBase_1.ModelBase;collection=null;xhr;withCredentials=!1;headers={};pending=!1;error=!1;completed=!1;saving=!1;changedExternal=!1;watch=!0;status=null;autoSave=!1;autoSaveInterval=4e3;autoSaveHalt=!0;autoSaveTimeout=null;urlSync=!1;bracket={match:/\[[\d+]]/,search:/\[([\d+])]/g,attr:/(^[^[]+)/};throttle=lodash_1.throttle(this.fetch,1e3);initialize=null;constructor(options={},attributes){if(super(attributes),(options="object"!=typeof options?{}:options).received=options.received||!1,lodash_1.extend(this,this.sanitizeOptions(options)),options.convoy){const convoy=misc_1.isJSON(options.convoy)?JSON.parse(options.convoy):options.convoy;if(lodash_1.isObject(convoy)){this.meta.set(convoy.meta||{});const payload=convoy.payload;lodash_1.isObject(payload)?(lodash_1.extend(this.data,payload),this.completed=!0,options.received=!0):console.error("malformed payload:",payload)}else console.error("malformed convoy:",convoy)}if(options.payload){const payload=misc_1.isJSON(options.payload)?JSON.parse(options.payload):options.payload;lodash_1.isObject(payload)?(lodash_1.extend(this.data,payload),this.completed=!0,options.received=!0):console.error("malformed payload:",payload)}this.header=new modelBase_1.ModelBase,this.meta=new modelBase_1.ModelBase,this.route=new modelBase_1.ModelBase,lodash_1.isEmpty(this.collection)||(this.collection.target&&(this.target=this.collection.target),this.collection.meta.has("api")&&this.meta.set("api",this.collection.meta.get("api"))),this.recv=options.received?lodash_1.cloneDeep(this.data):{},this.sent={},this.ignoreKeys=options.ignoreKeys||["$$hashKey"],this.target&&(this.urlRoot+="/"+misc_1.ucfirst(this.target));const that=this;this.initialize=lodash_1.once(this.initialize||function(){that.completed&&(that.watch||that.autoSave)&&that.watcher().then(),that.manifest&&!that.getIdentifier()&&that.sync("POST",that.meta.has("api")?{meta:that.meta.get("api"),payload:{}}:{}).catch(async error=>{if(console.error("MANIFEST:",error),!that.toast)return;const errorMessage=that.errorMessage(error),formatMessage=errorMessage?`: ${errorMessage}`:".";toastify_js_1.default({text:`Unable to Manifest ${that.target}${formatMessage}`,duration:12e3,close:!0,stopOnFocus:!0,style:{background:"#E14D45"}}).showToast(),that.errorMessage(error)})}),this.stagger||this.initialize()}resetXHRFlags(){this.pending=!1,this.saving=!1}sanitizeOptions(options){const sanitizedOptions={};return lodash_1.forEach(ModelOptionKeys,key=>{const data=lodash_1.get(options,key);lodash_1.isUndefined(data)||lodash_1.set(sanitizedOptions,key,data)}),sanitizedOptions}async watcher(){if(this.watching)return!0;this.watching=!0,$rootScope||await serviceVerify(),$rootScope.$watch(()=>this.data,(_newData,_priorData)=>this.handleChanges(),!0)}handleChanges(changeSet){const isUserChangeSet=lodash_1.isUndefined(changeSet);if(isUserChangeSet&&(changeSet=super.handleChanges()),!changeSet||lodash_1.isEmpty(changeSet))return changeSet;if(this.error&&!this.completed&&this.getIdentifier()){const action=isUserChangeSet?"save":"sync url for";return void console.warn(`Blocked attempt to ${action} a persisted model that has not been fetched successfully.`)}if(isUserChangeSet||environment_1.cookie("env")&&console.info("Attempting URL Sync for non-User ChangeSet:",changeSet),this.urlSync){if(lodash_1.get(changeSet,"id")){const newUrl=misc_1.setUrlParams({id:lodash_1.get(changeSet,"id")||this.getIdentifier()});newUrl!==document.location.href&&window.location.replace(newUrl)}const version=misc_1.getAnchorParams("version"),versionId=lodash_1.isEmpty(version)?0:parseInt(version,10);versionId&&versionId!==lodash_1.get(changeSet,"version.id")&&environment_1.cookie("env")&&console.warn("replacing version:",versionId)}return isUserChangeSet?(this.saveIdle(),this.throttleTrigger("change",this),this.collection&&this.collection.throttleTrigger("change",this),changeSet):void 0}getIdentifier(){return this.identifier=this.get("id")||this.route.get("identifier")||this.identifier}getType(){return this.type=this.type||this.target||"orphan"}getHash(){return this.getType()+(lodash_1.isNumber(this.getIdentifier())?this.getIdentifier().toString():this.getIdentifier())}isNew(){return!this.getIdentifier()}url(){let url=this.getIdentifier()?`${this.urlRoot}/${this.getIdentifier()}`:`${this.urlRoot}${this.targetSuffix||""}`;return misc_1.getUrlParams("version")&&(url+=url.includes("?")?"&":"?",url+="options[version]="+misc_1.getUrlParams("version")),url}serialize(obj,chain){return misc_1.serializeUrlParams(obj,chain)}sync(action,data,options){return this.pending=!0,this.trigger("change",this),this.collection&&(this.collection.pending=!0,this.collection.throttleTrigger("change")),this.sent=lodash_1.cloneDeep(this.data),new Promise(async(resolve,reject)=>{options=options||{};const request={method:action=action||"GET",url:this.url(),headers:lodash_1.clone(this.headers),withCredentials:this.withCredentials};lodash_1.isUndefined(data)||(["GET","DELETE"].includes(action)?lodash_1.isObject(data)&&Object.keys(data).length&&(request.url+=request.url.includes("?")?"&":"?",request.url+=this.serialize(data)):(request.headers["Content-Type"]="application/json",request.data=data)),environment_1.cookie("env")&&console.log("Prototype:",request),Object.prototype.hasOwnProperty.call(options,"headers")&&"object"==typeof options.headers&&Object.keys(options.headers).forEach(headerKey=>{request.headers[headerKey]=options.headers[headerKey]}),this.xhr=new xhr_1.XHR(request),this.xhr.send().then(response=>{this.status=this.xhr.status,(this.watch||this.autoSave)&&this.watcher();const propagateError=()=>{this.error=!0,this.resetXHRFlags(),this.collection&&(this.collection.pending=!1),this.trigger("error",this),this.trigger("complete",this),this.collection instanceof collection_1.Collection&&this.collection.throttleTrigger("change")};if(!lodash_1.isObject(response)&&!lodash_1.isArray(response)){const error=new errorBase_1.ErrorBase({payload:response,message:`Invalid Payload: ${request.method} ${request.url}`},{});return propagateError(),void reject(error)}this.header.set(this.xhr.getAllResponseHeaders()||{}),this.meta.set(response.meta||{}),this.route.set(response.route||{});const payload=response.payload||response;if(this.error=!1,this.meta.has("success")&&!this.meta.get("success")?this.error=!0:lodash_1.isArray(payload)&&payload.length?this.recv=lodash_1.head(payload):lodash_1.isObject(payload)&&!lodash_1.isArray(payload)?this.recv=payload:(this.meta.has("status")||this.meta.has("success")||(this.error=!0),console.warn(`Invalid Payload: ${request.method} ${request.url}`)),this.error){const error=new errorBase_1.ErrorBase({payload,message:`Invalid Payload: ${request.method} ${request.url}`},{});return propagateError(),void reject(error)}const incomingChangeSet=this.completed?lodash_1.cloneDeep(misc_1.patch(this.recv,this.sent)):{};lodash_1.isEmpty(incomingChangeSet)||(environment_1.cookie("env")&&console.log("Incoming ChangeSet detected:",environment_1.cookie("debug_change_set")?JSON.stringify(incomingChangeSet):incomingChangeSet),this.handleChanges(incomingChangeSet));const intermediateData=lodash_1.cloneDeep(this.recv),intermediateChangeSet=lodash_1.cloneDeep(misc_1.patch(this.data,this.sent));lodash_1.isEmpty(intermediateChangeSet)||(environment_1.cookie("env")&&console.log("Intermediate ChangeSet detected:",environment_1.cookie("debug_change_set")?JSON.stringify(intermediateChangeSet):intermediateChangeSet),lodash_1.forEach(intermediateChangeSet,(element,key)=>{lodash_1.set(intermediateData,key,element)})),this.data=lodash_1.cloneDeep(intermediateData),this.changed=!1,this.changedExternal=!1,this.saving=!1,this.handleChanges(),this.patch={},this.resetXHRFlags(),this.completed=!0,this.collection&&(this.collection.pending=!1),this.meta.clearTemp(),this.trigger("success",this),this.trigger("change",this),this.trigger("complete",this),this.collection instanceof collection_1.Collection&&this.collection.throttleTrigger("change"),resolve(this.data)}).catch(error=>{this.status=500,this.error=!0,this.resetXHRFlags(),console.error(`XHR: ${request.method} ${request.url}`,error),reject(error)})})}fetch(action,data,options){return new Promise(async(resolve,reject)=>{this.sync(action,data||this.meta.get("api"),options).then(resolve).catch(async error=>{if(this.status=500,this.error=!0,this.resetXHRFlags(),console.error("FETCH:",error),!this.toast)return void reject(error);const errorMessage=this.errorMessage(error),formatMessage=errorMessage?`: ${errorMessage}`:".";toastify_js_1.default({text:`Unable to Fetch ${this.target}${formatMessage}`,duration:12e3,close:!0,stopOnFocus:!0,style:{background:"#E14D45"}}).showToast(),reject(error)})})}save(options){return this.saving=!0,options=options||{},lodash_1.isObject(options)||(console.warn("invalid options supplied:",options),options={}),lodash_1.has(options,"force")&&options.force?(options.patch=!!lodash_1.has(options,"patch")&&options.patch,this.doSave(options)):this.isNew()||!this.pending&&this.completed&&!lodash_1.isEmpty(this.toPatch())?this.doSave(options):(console.warn(`Blocked attempt to save ${lodash_1.isEmpty(this.toPatch())?"an empty payload":"a duplicate XHR"} to a persisted model.`),new Promise((resolve,_reject)=>{this.saving=!1,resolve(this.data)}))}doSave(options){return options=options||{},lodash_1.isObject(options)||(console.warn("invalid options supplied:",options),options={}),options.patch=!lodash_1.has(options,"patch")||options.patch,new Promise(async(resolve,reject)=>{this.sync(this.getIdentifier()?"PUT":"POST",this.toJSON({patch:options.patch})).then(resolve).catch(async error=>{if(this.error=!0,this.resetXHRFlags(),console.error("SAVE:",error),!this.toast)return void reject(error);const errorMessage=this.errorMessage(error),formatMessage=errorMessage?`: ${errorMessage}`:".";toastify_js_1.default({text:`Unable to Save ${this.target}${formatMessage}`,duration:12e3,close:!0,stopOnFocus:!0,style:{background:"#E14D45"}}).showToast(),reject(error)})})}saveIdle(){this.autoSaveTimeout&&clearTimeout(this.autoSaveTimeout),this.pending||!this.completed||this.isNew()||lodash_1.isEmpty(this.toPatch())||this.autoSaveHalt&&!this.autoSave||(this.autoSaveTimeout=setTimeout(()=>{this.autoSaveHalt||this.autoSave?this.save().then():this.saveIdle()},this.autoSaveInterval))}throttleSave(){return new Promise((resolve,reject)=>{const request=this.throttle();console.log("throttle request:",request),request.then(data=>{console.log("throttle received:",data),resolve(data)}).catch(reject)})}toJSON(options){options=options||{},lodash_1.isObject(options)||(options={}),options.patch=options.patch&&!this.isNew();let data=super.toJSON(options);const metaData=this.meta.get("api");return metaData&&(data={meta:metaData,payload:data}),data}buildPath(path){const acc=[];if(!lodash_1.isString(path))return acc;let cur,search;return lodash_1.forEach(path.split("."),link=>{if(link.match(this.bracket.match))for(cur=this.bracket.attr.exec(link),null!==cur?(acc.push(cur[1]),cur=null):cur=!1,search=this.bracket.search.exec(link);null!==search;)!1!==cur&&(cur=parseInt(search[1],10),isNaN(cur)?cur=!1:acc.push(cur)),search=this.bracket.search.exec(link);else acc.push(link)}),acc}get(attr){if("string"==typeof attr&&this.data&&"object"==typeof this.data)return lodash_1.get(this.data,attr)}find(attr,key,value){return"string"==typeof attr&&(attr=this.get(attr)),lodash_1.isArray(attr)?attr.find(obj=>obj[key]===value):attr}set(attr,value){return attr?"object"==typeof attr?(lodash_1.forEach(attr,(v,k)=>this.setAttribute(k,v)),this):(this.setAttribute(attr,value),this):(console.warn("No attr for model.set()!"),this)}setAttribute(attr,value){if("string"!=typeof attr)return console.warn("Malformed attr for model.setAttribute()!"),!1;lodash_1.set(this.data,attr,value),this.throttleTrigger("change",this),this.throttleTrigger(`change:${attr}`,value)}toggle(attribute,item,options){"object"==typeof options&&!lodash_1.isUndefined(options.multiple)&&lodash_1.isUndefined(options.strict)&&(options.strict=!0),options=lodash_1.extend({multiple:!0},lodash_1.isObject(options)?options:{});const request=attribute.split("[].");let target=this.get(request.length>1?request[0]:attribute);return(lodash_1.isUndefined(target)||options.strict&&lodash_1.isArray(target)!==options.multiple)&&(target=options.multiple?[]:null,this.set(request.length>1?request[0]:attribute,target)),lodash_1.isArray(target)?lodash_1.isUndefined(item)?this.set(attribute,null):this.exists(attribute,item)?lodash_1.forEach(target,(element,key)=>{const child=request.length>1&&"object"==typeof element&&request[1]in element?element[request[1]]:element,childId="object"==typeof child&&child.id?child.id:child,itemId="object"==typeof item&&item.id?item.id:item;(childId===itemId||lodash_1.isString(childId)&&lodash_1.isString(itemId)&&0===misc_1.strcmp(childId,itemId))&&target.splice(key,1)}):target.push(item):"object"==typeof target||"number"==typeof target?this.set(attribute,this.exists(attribute,item)?null:item):lodash_1.isUndefined(item)&&this.set(attribute,!target),this.get(attribute)}pluck(attr){if("string"!=typeof attr||-1===attr.indexOf("[]."))return this.get(attr);const request=attr.split("[].");if(request.length<=1)return;if(!(attr=this.get(request[0]))||!lodash_1.isArray(attr))return;const list=lodash_1.filter(lodash_1.map(attr,element=>lodash_1.get(element,request[1])));return list.length?list:void 0}exists(attribute,item){return item?!("string"!=typeof attribute||!item)&&(attribute=this.pluck(attribute),lodash_1.isArray(attribute)?void 0!==attribute.find(element=>element===item||"object"==typeof element&&element.id&&element.id===item||lodash_1.isEqual(element,item)):attribute===item||"object"==typeof attribute&&attribute.id&&(lodash_1.isEqual(attribute,item)||attribute.id===item)):void 0!==(attribute=this.get(attribute))&&attribute}destroy(){return this.isNew()?new Promise((resolve,_reject)=>{this.throttleTrigger("change"),this.collection&&this.collection.remove(this),resolve(this.data)}):new Promise(async(_resolve,reject)=>{let deleteData={};lodash_1.isEmpty(this.meta.get("api"))||(deleteData=this.meta.get("api")),this.sync("DELETE",deleteData).then(_data=>{this.error?reject(this.error):(this.throttleTrigger("change"),this.collection&&this.collection.remove(this),_resolve(this.data))}).catch(async error=>{if(this.error=!0,this.resetXHRFlags(),console.error("DESTROY:",error),!this.toast)return void reject(error);const errorMessage=this.errorMessage(error),formatMessage=errorMessage?`: ${errorMessage}`:".";toastify_js_1.default({text:`Unable to Delete ${this.target}${formatMessage}`,duration:12e3,close:!0,stopOnFocus:!0,style:{background:"#E14D45"}}).showToast(),reject(error)})})}errorMessage(error){if(error instanceof errorBase_1.ErrorBase)return console.error(`[${error.code}] ${error.message}`,error),"Internal"!==error.code?error.message:null;const digest=error.responseText&&misc_1.isJSON(error.responseText)?JSON.parse(error.responseText):null;if(!digest)return null;const message=lodash_1.get(digest,"meta.status[0].message")||lodash_1.get(digest,"error.exception[0].message")||null;return message?!environment_1.cookie("env")&&lodash_1.has(digest,"error.exception[0].message")?(console.error("[xhr] server:",message),null):message:null}},exports_1("Model",Model),stratus_1.Stratus.Services.Model=["$provide",$provide=>{$provide.factory("Model",[()=>Model])}],stratus_1.Stratus.Data.Model=Model}}});