DockerERTFF/public/dmxAppConnect/dmxPouchDB/dmxPouchDB.js

9 lines
12 KiB
JavaScript

/*!
Wappler PouchDB
Version: 1.0.0
(c) 2024 Wappler.io
@build 2024-04-15 17:48:46
*/
dmx.databases=dmx.databases||{},dmx.pouchdb={databases:new Map,setup(t,e={}){if(!this.databases.has(t)){const s=new PouchDB(t,{...e,adapter:"indexeddb"});return s.setMaxListeners(0),this.databases.set(t,s),s.info().then((e=>{console.log(`PouchDB: ${t}`,e)})),s}return this.databases.get(t)},get(t){return this.setup(t)}},dmx.Startup(new Promise(((t,e)=>{document.addEventListener("DOMContentLoaded",t)})).then((()=>{if(dmx.databases&&Object.keys(dmx.databases).length)return dmx.debug&&console.log("dmx.databases:",dmx.databases),Promise.all(Object.keys(dmx.databases).filter((t=>"pouchdb"===dmx.databases[t].type)).map((t=>{const{version:e,upgrade:s,remote:n,options:a}=dmx.databases[t],i=dmx.pouchdb.setup(t,{options:a});return n?(dmx.debug&&console.log(`${t} replicate from ${n}`),i.replicate.from(n).then((()=>{dmx.debug&&console.log(`${t} replication done, init sync`),i.sync(n,{live:!0,retry:!0}).on("change",(e=>{document.dispatchEvent(new CustomEvent("pouchdb:sync",{detail:{database:t,change:e}})),dmx.debug&&console.log(`${t} sync change`,e)})).on("error",(e=>{document.dispatchEvent(new CustomEvent("pouchdb:error",{detail:{database:t,err:e}})),dmx.debug&&console.log(`${t} sync error`,e)}))})).catch((e=>{console.warn(`Replication error for ${t}:`,e)}))):(dmx.debug&&console.log(`upgrade ${t} to version ${e}`),i.get("_local/version").then((t=>t.version)).catch((t=>0)).then((e=>(dmx.debug&&console.log(`${t} current version ${e}`),Promise.all(s.map((s=>{if(!(e>=s.toVersion))return dmx.debug&&console.log(`Upgrade ${t} to ${s.toVersion}`),i.bulkDocs(s.updates.concat([{_id:"_local/version",version:s.toVersion}])).then((e=>(dmx.debug&&console.log(`Upgrade result for ${t}:`,e),Promise.all(e.filter((t=>409==t.status)).map((t=>(dmx.debug&&console.log("Conflict",t),i.get(t.id).then((t=>(dmx.debug&&(console.log("Conflict doc",t),console.log("Conflict update",s.updates.find((e=>e._id==t._id)))),i.put({...t,...s.updates.find((e=>e._id==t._id)),version:s.toVersion}))))))))))).catch((e=>{console.error(`Upgrade error for ${t}:`,e)}));dmx.debug&&console.log(`Skipping upgrade for ${t}:`,s)})))))))})))}))),function(){const t=t=>t.rows.map((t=>t.doc)),e=t=>e=>{if(t){const s=(t,e)=>{if(e.operator){const s=t[e.data.column],n=e.value;switch(e.operator){case"equal":return s==n;case"not_equal":return s!=n;case"in":return n.includes(s);case"not_in":return!n.includes(s);case"less":return s<n;case"less_or_equal":return s<=n;case"greater":return s>n;case"greater_or_equal":return s>=n;case"between":return n[0]<=s<=n[1];case"not_between":return!(n[0]<=s<=n[1]);case"begins_with":return String(s).startsWith(String(n));case"not_begins_with":return!String(s).startsWith(String(n));case"contains":return String(s).includes(String(n));case"not_contains":return!String(s).includes(String(n));case"ends_with":return String(s).endsWith(String(n));case"not_ends_with":return!String(s).endsWith(String(n));case"is_empty":return null==s||""==s;case"is_not_empty":return null!=s&&""!=s;case"is_null":return null==s;case"is_not_null":return null!=s}}if(e.condition&&e.rules.length){for(let n of e.rules){const a=s(t,n);if(!a&&"AND"==e.condition)return!1;if(a&&"OR"==e.condition)return!0}return"OR"!=e.condition}return!0};return e.filter((e=>s(e,t)))}return e},s=t=>e=>e.sort(((e,s)=>{for(let n of t){if(e[n.column]==s[n.column])continue;let t=n.direction&&"desc"==n.direction.toLowerCase();return e[n.column]<s[n.column]?t?1:-1:t?-1:1}return 0})),n=t=>e=>!Array.isArray(t)||1==t.length&&"*"==t[0].column?e:e.map((e=>{const s={};for(let n of t)"*"==n.column?Object.assign(s,e):s[n.alias||n.column||n]=e[n.column||n];return s})),a=t=>e=>t?[...new Set(e)]:e,i=(t,e,s)=>n=>{const a=n.length;return t=Number(t||0),e=Number(e||0),n=n.slice(t,e?t+e:void 0),s?{offset:t,limit:e,total:a,page:{offset:{first:0,prev:t-e>0?t-e:0,next:t+e<a?t+e:t,last:(Math.ceil(a/e)-1)*e},current:Math.floor(t/e)+1,total:Math.ceil(a/e)},data:n}:n};dmx.Actions({"pouchdb.select"(o){const r=this.parse(o),d=dmx.pouchdb.get(r.connection),c=r.sql,h=c.table.name||c.table;return d.allDocs({startkey:h+"/",endkey:h+"/￿",include_docs:!0}).then(t).then(e(c.wheres)).then(s(c.orders)).then(n(c.columns)).then(a(c.distinct)).then(i(c.offset,c.limit,!1))},"pouchdb.single":function(i){const o=this.parse(i),r=dmx.pouchdb.get(o.connection),d=o.sql,c=d.table.name||d.table;return r.allDocs({startkey:c+"/",endkey:c+"/￿",include_docs:!0}).then(t).then(e(d.wheres)).then(s(d.orders)).then(n(d.columns)).then(a(d.distinct)).then((t=>t[0]))},"pouchdb.paged":function(o){const r=this.parse(o),d=dmx.pouchdb.get(r.connection),c=r.sql,h=c.table.name||c.table;return d.allDocs({startkey:h+"/",endkey:h+"/￿",include_docs:!0}).then(t).then(e(c.wheres)).then(s(c.orders)).then(n(c.columns)).then(a(c.distinct)).then(i(c.offset,c.limit,!0))},"pouchdb.insert":function(t){const e=this.parse(t),s=dmx.pouchdb.get(e.connection),n=e.sql,a={};for(let t of n.values)a[t.column]=t.value;return a._id=n.table+"/"+Date.now(),s.put(a).then((t=>({affected:t.ok?1:0,identity:t.id})))},"pouchdb.update":function(s){const n=this.parse(s),a=dmx.pouchdb.get(n.connection),i=n.sql;return a.allDocs({startkey:i.table+"/",endkey:i.table+"/￿",include_docs:!0}).then(t).then(e(i.wheres)).then((t=>a.bulkDocs(t.map((t=>{for(let e of i.values)t[e.column]=e.value;return t}))))).then((t=>({affected:t.filter((t=>t.ok)).length})))},"pouchdb.delete":function(s){const n=this.parse(s),a=dmx.pouchdb.get(n.connection),i=n.sql;return a.allDocs({startkey:i.table+"/",endkey:i.table+"/￿",include_docs:!0}).then(t).then(e(i.wheres)).then((t=>a.bulkDocs(t.map((t=>({_deleted:!0,_id:t._id,_rev:t._rev})))))).then((t=>({affected:t.filter((t=>t.ok)).length})))},"pouchdb.get":function(t){const{connection:e,docId:s,attachments:n}=this.parse(t);return dmx.pouchdb.get(e).get(s,{attachments:n})},"pouchdb.getAttachment":function(t){const{connection:e,docId:s,name:n}=this.parse(t);return dmx.pouchdb.get(e).getAttachment(s,n).then((t=>dmx.fileUtils.blobToDataURL(t)))},"pouchdb.putAttachment":function(t){const{connection:e,docId:s,name:n,dataURL:a}=this.parse(t),{data:i,type:o}=dmx.fileUtils.parseDataURL(a),r=dmx.pouchdb.get(e),d=r.get(s);return r.putAttachment(d._id,n,d._rev,i,o)},"pouchdb.removeAttachment":function(t){const{connection:e,docId:s,name:n}=this.parse(t),a=dmx.pouchdb.get(e),i=a.get(s);return a.removeAttachment(i._id,n,i._rev)}})}(),dmx.Component("pouchdb",{attributes:{db:{type:String,default:null}},methods:{replicateFrom(t){return this._db.replicate.from(dmx.pouchdb.get(t))},replicateTo(t){return this._db.replicate.to(dmx.pouchdb.get(t))}},events:{change:Event,error:Event,sync:Event},init(){document.addEventListener("pouchdb:sync",(t=>{t.detail.database===this.props.db&&this.dispatchEvent("sync",null,t.detail.change)})),document.addEventListener("pouchdb:error",(t=>{t.detail.database===this.props.db&&this.dispatchEvent("error",null,t.detail.change)})),this._initDatabase()},performUpdate(t){t.has("db")&&this._initDatabase()},destroy(){this._changes&&(this._changes.cancel(),this._changes=null)},_initDatabase(){this._changes&&this._changes.cancel(),this.props.db&&(this._db=dmx.pouchdb.get(this.props.db),this._changes=this._db.changes({live:!0,include_docs:!0,since:"now"}).on("change",(t=>{dmx.debug&&console.debug(`${this.name}:changes:change`,t),this.dispatchEvent("change",null,t)})).on("error",(t=>{dmx.debug&&console.debug(`${this.name}:changes:error`,t),this.dispatchEvent("error",null,t)})))}}),dmx.Component("pouchdb-view",{initialData:{data:[],page:1,pages:1,items:0,sort:{on:"",dir:"asc"},has:{first:!1,prev:!1,next:!1,last:!1}},attributes:{db:{type:String,default:""},collection:{type:String,default:""},filter:{type:String,default:""},page:{type:Number,default:1},pagesize:{type:Number,default:0},sorton:{type:String,default:""},sortdir:{type:String,default:"asc",enum:["asc","desc"]}},methods:{select(t){this._updatePage(+t)},first(){this._updatePage(1)},prev(){this._updatePage(this.data.page-1)},next(){this._updatePage(this.data.page+1)},last(){this._updatePage(this.data.pages)},sort(t,e){this.props.sorton=t,this.props.sortdir=e&&"desc"==e.toLowerCase()?"desc":"asc"}},events:{change:Event,updated:Event,error:Event},init(){this._docs=[],this._items=[],this._initDatabase(),this.props.filter&&this._updateFilter()},performUpdate(t){t.has("db")?this._initDatabase():t.has("collection")?this._updateDocs():t.has("filter")?this._updateFilter():t.has("sorton")||t.has("sortdir")?this._updateData():(t.has("page")||t.has("pagesize"))&&this._updatePage(this.props.page)},destroy(){this._changes&&(this._changes.cancel(),this._changes=null),this._filterEffect&&(this._filterEffect(),this._filterEffect=null)},_initDatabase(){this._db=null,this._changes&&this._changes.cancel(),this.props.db&&(this._db=dmx.pouchdb.get(this.props.db),this._changes=this._db.changes({live:!0,include_docs:!0,since:"now",filter:t=>t._id.startsWith(this.props.collection+"/")}).on("change",(t=>{dmx.debug&&console.debug(`${this.name}:changes:change`,t),this._updateDocs(),this.dispatchEvent("change",null,t)})).on("error",(t=>{dmx.debug&&console.debug(`${this.name}:changes:error`,t),this.dispatchEvent("error",null,t)})),this.props.page>1&&this.set("page",this.props.page),this._updateDocs())},_updateDocs(){if(!this._db)return;const{collection:t}=this.props;t?this._db.allDocs({startkey:t+"/",endkey:t+"/￿",include_docs:!0}).then((t=>t.rows.map((t=>t.doc)))).then((t=>{dmx.debug&&console.debug(`${this.name}:query:result`,t),this._docs=t,this._updateData(),dmx.nextTick((()=>this.dispatchEvent("updated")))})).catch((t=>{dmx.debug&&console.debug(`${this.name}:query:error`,t),this.dispatchEvent("error",null,t)})):(this._docs=[],this._updateData(),dmx.nextTick((()=>this.dispatchEvent("updated"))))},_updateFilter(){this._filterEffect&&(this._filterEffect(),this._filterEffect=null),this.props.filter&&(this._filterEffect=dmx.effect((()=>{dmx.parse(this.props.filter,this),this._updateData()})))},_updateData(){this._items=this._docs,this.props.filter&&(this._items=this._docs.filter((t=>dmx.parse(this.props.filter,dmx.DataScope(t,this)))));let{sorton:t,sortdir:e,pagesize:s}=this.props,n=this._items.length,a=s?Math.max(1,Math.ceil(n/s)):1;if(t){const s="desc"===e;this._items.sort(((e,n)=>s?e[t]>n[t]?-1:e[t]<n[t]?1:0:e[t]<n[t]?-1:e[t]>n[t]?1:0))}this.set({pages:a,items:n}),this._updatePage(this.data.page||this.props.page)},_updatePage(t){const e=this.props.pagesize,s=this.data.pages,n=((t=t<1?1:t>s?s:t)-1)*e;this.set({page:t,data:e?this._items.slice(n,n+e):this._items,has:{first:t>1,prev:t>1,next:t<s,last:t<s}})}}),dmx.Component("pouchdb-detail",{initialData:{data:{},stale:!1},attributes:{db:{type:String,default:null},docid:{type:String,default:null},attachments:{type:Boolean,default:!1},autoupdate:{type:Boolean,default:!1}},methods:{select(t){this.props.docid=t},refresh(){this._getDoc(this.props.docid)}},events:{change:Event,error:Event},init(){this.props.db&&this._initDatabase()},performUpdate(t){t.has("db")?this._initDatabase():this._getDoc()},destroy(){this._cancelChanges()},_initDatabase(){this._cancelChanges(),this.props.db?(this._db=dmx.pouchdb.get(this.props.db),this.props.docid&&this._getDoc()):this._db=null},_getDoc(){this._cancelChanges(),this._db&&(this.props.docid?(this._db.get(this.props.docid,{attachments:this.props.attachments}).then((t=>{this.set({data:t,stale:!1})})),this._changes=this._db.changes({live:!0,include_docs:!0,attachments:this.props.attachments,since:"now",doc_ids:[this.props.docid]}).on("change",(t=>{dmx.debug&&console.debug(`${this.name}:changes:change`,t),this.props.autoupdate?this.set({data:t.doc,stale:!1}):this.set("stale",!0),this.dispatchEvent("change",null,t)})).on("error",(t=>{dmx.debug&&console.debug(`${this.name}:changes:error`,t),this.set({data:{},stale:!0}),this.dispatchEvent("error",null,t)}))):this.set({data:{},stale:!1}))},_cancelChanges(){this._changes&&(dmx.debug&&console.log("cancel changes",this._changes),this._changes.cancel(),this._changes=null)}});
//# sourceMappingURL=dmxPouchDB.js.map