@flumens/models 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -59,18 +59,6 @@ export default class Occurrence<T extends Attrs = Attrs, S extends Metadata = Me
59
59
  taxon: {
60
60
  id: string;
61
61
  };
62
- comment: {
63
- id: string;
64
- };
65
- releaseStatus: {
66
- id: string;
67
- };
68
- recordStatus: {
69
- id: string;
70
- };
71
- sensitivityPrecision: {
72
- id: string;
73
- };
74
62
  training: {
75
63
  id: string;
76
64
  values: (val?: boolean | "t" | "f" | null | undefined) => "t" | "f";
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),r=require("lodash"),i=require("../Model.js"),a=require("./Media.js"),n=require("./helpers.js"),o=function(i){function o(r){var a=this;void 0===r&&(r={});var n=r.metadata,s=void 0===n?{}:n,u=r.media,d=void 0===u?[]:u,c=t.__rest(r,["metadata","media"]);(a=i.call(this,c)||this).debouncedValue=300,a.keys=function(){var e;return t.__assign(t.__assign({},o.keys),(e=a.getSurvey().attrs||{},Object.keys(e).reduce((function(r,i){var a;return t.__assign(t.__assign({},r),((a={})[i]=e[i].remote||e[i],a))}),{})))},a.metadata=e.observable(s),a.media=e.observable(d);var l=function(t){return t.parent=a};a.media.forEach(l);return e.intercept(a.media,(function(t){var e;return(null===(e=t.added)||void 0===e?void 0:e.length)?(t.added.forEach(l),a.setUpdatedAtTimestamp(Date.now())):t.removedCount&&a.setUpdatedAtTimestamp(Date.now()),t})),a}return t.__extends(o,i),o.fromJSON=function(e,r){var i,n,o,s;return void 0===r&&(r=a.default),new this(t.__assign(t.__assign({},e),{createdAt:e.createdAt||(null===(i=e.metadata)||void 0===i?void 0:i.createdOn),updatedAt:e.updatedAt||(null===(n=e.metadata)||void 0===n?void 0:n.updatedOn),syncedAt:e.syncedAt||(null===(o=e.metadata)||void 0===o?void 0:o.syncedOn),media:null===(s=e.media)||void 0===s?void 0:s.map((function(t){return r.fromJSON(t)}))}))},o.prototype.setUpdatedAtTimestamp=function(t){var e;i.prototype.setUpdatedAtTimestamp.call(this,t),null===(e=this.parent)||void 0===e||e.setUpdatedAtTimestamp(t)},o.prototype.save=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){if(!this.parent)throw new Error("Trying to save locally without a parent");return this.parent.save(),[2]}))}))},o.prototype.destroy=function(e){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:if(!this.parent)throw new Error("Trying to destroy locally without a parent");return this.parent.occurrences.remove(this),[4,Promise.all(this.media.map((function(t){return t.destroy(!0)})))];case 1:return t.sent(),e?[2]:[4,this.parent.save()];case 2:return t.sent(),[2]}}))}))},o.prototype.sync=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){return[2,this.parent?this.parent.sync():i.prototype.sync.call(this)]}))}))},o.prototype.toJSON=function(){var r,a=i.prototype.toJSON.call(this);return JSON.parse(JSON.stringify(t.__assign(t.__assign({},a),{media:(null===(r=this.media)||void 0===r?void 0:r.map((function(t){return t.toJSON()})))||[],metadata:e.toJS(this.metadata)||{}})))},o.prototype.getSurvey=function(){return this.parent&&this.parent.getSurvey().occ||{}},o.prototype.isUploaded=function(){if(!this.parent)throw new Error("No occurrence parent to return disabled status.");return this.parent.isUploaded()},o.prototype.isDisabled=function(){return this.isUploaded()},o.prototype.getSubmission=function(e){var i=this;void 0===e&&(e={});var a="function"==typeof this.keys?this.keys():this.keys,n=t.__assign(t.__assign({},o.keys),a),s={values:{external_key:this.cid},media:[]};this.id&&(s.values.id=this.id);Object.keys(this.attrs).forEach((function(t){var e=i.attrs[t],a=function(t){return null==t};if(!a(e)){if(!n[t])return t=t.includes("occAttr:")?t:r.snakeCase(t),void(s.values[t]=e);var o=n[t].id||t;if(e=function(t,e){var r=n[t].values;if(!r)return e;if("function"==typeof r)return r(e,s,i);if(r instanceof Array){var a=r.find((function(t){return t.value===e}));if(!a||!a.id)throw new Error('A "'.concat(t,'" attribute "').concat(e,'" value could not be mapped to a remote database field.'));return a.id}return e instanceof Array?e.map((function(t){return r[t]})):r[e]}(t,e),!a(e)){var u=Number.isNaN(Number(o))?o:"occAttr:".concat(o);u=u.includes("occAttr:")?u:r.snakeCase(u),s.values[u]=e}}})),this.media.forEach((function(t){var r=t.getSubmission(e);r&&s.media.push(r)}));var u=this.getSurvey();return u.modifySubmission?u.modifySubmission(s,this):s},o.keys={taxon:{id:"taxa_taxon_list_id"},comment:{id:"comment"},releaseStatus:{id:"release_status"},recordStatus:{id:"record_status"},sensitivityPrecision:{id:"sensitivity_precision"},training:{id:"training",values:n.boolToWarehouseValue},deleted:{id:"deleted",values:n.boolToWarehouseValue},confidential:{id:"confidential",values:n.boolToWarehouseValue},zeroAbundance:{id:"zero_abundance",values:n.boolToWarehouseValue}},o}(i.default);exports.default=o;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),r=require("lodash"),i=require("../Model.js"),a=require("./Media.js"),n=require("./helpers.js"),o=function(i){function o(r){var a=this;void 0===r&&(r={});var n=r.metadata,s=void 0===n?{}:n,u=r.media,d=void 0===u?[]:u,c=t.__rest(r,["metadata","media"]);(a=i.call(this,c)||this).debouncedValue=300,a.keys=function(){var e;return t.__assign(t.__assign({},o.keys),(e=a.getSurvey().attrs||{},Object.keys(e).reduce((function(r,i){var a;return t.__assign(t.__assign({},r),((a={})[i]=e[i].remote||e[i],a))}),{})))},a.metadata=e.observable(s),a.media=e.observable(d);var l=function(t){return t.parent=a};a.media.forEach(l);return e.intercept(a.media,(function(t){var e;return(null===(e=t.added)||void 0===e?void 0:e.length)?(t.added.forEach(l),a.setUpdatedAtTimestamp(Date.now())):t.removedCount&&a.setUpdatedAtTimestamp(Date.now()),t})),a}return t.__extends(o,i),o.fromJSON=function(e,r){var i,n,o,s;return void 0===r&&(r=a.default),new this(t.__assign(t.__assign({},e),{createdAt:e.createdAt||(null===(i=e.metadata)||void 0===i?void 0:i.createdOn),updatedAt:e.updatedAt||(null===(n=e.metadata)||void 0===n?void 0:n.updatedOn),syncedAt:e.syncedAt||(null===(o=e.metadata)||void 0===o?void 0:o.syncedOn),media:null===(s=e.media)||void 0===s?void 0:s.map((function(t){return r.fromJSON(t)}))}))},o.prototype.setUpdatedAtTimestamp=function(t){var e;i.prototype.setUpdatedAtTimestamp.call(this,t),null===(e=this.parent)||void 0===e||e.setUpdatedAtTimestamp(t)},o.prototype.save=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){if(!this.parent)throw new Error("Trying to save locally without a parent");return this.parent.save(),[2]}))}))},o.prototype.destroy=function(e){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:if(!this.parent)throw new Error("Trying to destroy locally without a parent");return this.parent.occurrences.remove(this),[4,Promise.all(this.media.map((function(t){return t.destroy(!0)})))];case 1:return t.sent(),e?[2]:[4,this.parent.save()];case 2:return t.sent(),[2]}}))}))},o.prototype.sync=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){return[2,this.parent?this.parent.sync():i.prototype.sync.call(this)]}))}))},o.prototype.toJSON=function(){var r,a=i.prototype.toJSON.call(this);return JSON.parse(JSON.stringify(t.__assign(t.__assign({},a),{media:(null===(r=this.media)||void 0===r?void 0:r.map((function(t){return t.toJSON()})))||[],metadata:e.toJS(this.metadata)||{}})))},o.prototype.getSurvey=function(){return this.parent&&this.parent.getSurvey().occ||{}},o.prototype.isUploaded=function(){if(!this.parent)throw new Error("No occurrence parent to return disabled status.");return this.parent.isUploaded()},o.prototype.isDisabled=function(){return this.isUploaded()},o.prototype.getSubmission=function(e){var i=this;void 0===e&&(e={});var a="function"==typeof this.keys?this.keys():this.keys,n=t.__assign(t.__assign({},o.keys),a),s={values:{external_key:this.cid},media:[]};this.id&&(s.values.id=this.id);Object.keys(this.attrs).forEach((function(t){var e=i.attrs[t],a=function(t){return null==t};if(!a(e)){if(!n[t])return t=t.includes("occAttr:")?t:r.snakeCase(t),void(s.values[t]=e);var o=n[t].id||t;if(e=function(t,e){var r=n[t].values;if(!r)return e;if("function"==typeof r)return r(e,s,i);if(r instanceof Array){var a=r.find((function(t){return t.value===e}));if(!a||!a.id)throw new Error('A "'.concat(t,'" attribute "').concat(e,'" value could not be mapped to a remote database field.'));return a.id}return e instanceof Array?e.map((function(t){return r[t]})):r[e]}(t,e),!a(e)){var u=Number.isNaN(Number(o))?o:"occAttr:".concat(o);u=u.includes("occAttr:")?u:r.snakeCase(u),s.values[u]=e}}})),this.media.forEach((function(t){var r=t.getSubmission(e);r&&s.media.push(r)}));var u=this.getSurvey();return u.modifySubmission?u.modifySubmission(s,this):s},o.keys={taxon:{id:"taxa_taxon_list_id"},training:{id:"training",values:n.boolToWarehouseValue},deleted:{id:"deleted",values:n.boolToWarehouseValue},confidential:{id:"confidential",values:n.boolToWarehouseValue},zeroAbundance:{id:"zero_abundance",values:n.boolToWarehouseValue}},o}(i.default);exports.default=o;
@@ -25,7 +25,7 @@ export interface Attrs extends AttrsOriginal {
25
25
  */
26
26
  inputForm?: string | null;
27
27
  date?: any;
28
- location_type?: any;
28
+ locationType?: any;
29
29
  /**
30
30
  * Allows record precision to be blurred for public viewing for privacy
31
31
  * (as opposed to sensitivity) reasons. An example might be to obscure
@@ -62,21 +62,12 @@ export interface Survey extends BaseSurvey {
62
62
  occ?: BaseSurvey;
63
63
  }
64
64
  declare class Sample<T extends Attrs = Attrs, S extends Metadata = Metadata> extends Model {
65
- static fromJSON(json: any, OccurrenceClass?: any, Sample?: any, // eslint-disable-line
65
+ static fromJSON(jsonProp: any, OccurrenceClass?: any, Sample?: any, // eslint-disable-line
66
66
  MediaClass?: any): Sample<Attrs, Metadata>;
67
67
  /**
68
68
  * Warehouse attributes and their values.
69
69
  */
70
70
  static keys: {
71
- surveyId: {
72
- id: string;
73
- };
74
- date: {
75
- id: string;
76
- };
77
- sample_method_id: {
78
- id: string;
79
- };
80
71
  location: {
81
72
  id: string;
82
73
  };
@@ -89,15 +80,9 @@ declare class Sample<T extends Attrs = Attrs, S extends Metadata = Metadata> ext
89
80
  latlon: number;
90
81
  };
91
82
  };
92
- inputForm: {
93
- id: string;
94
- };
95
83
  group: {
96
84
  id: string;
97
85
  };
98
- comment: {
99
- id: string;
100
- };
101
86
  training: {
102
87
  id: string;
103
88
  values: (val?: boolean | "t" | "f" | null | undefined) => "t" | "f";
@@ -106,17 +91,11 @@ declare class Sample<T extends Attrs = Attrs, S extends Metadata = Metadata> ext
106
91
  id: string;
107
92
  values: (val?: boolean | "t" | "f" | null | undefined) => "t" | "f";
108
93
  };
109
- privacyPrecision: {
110
- id: string;
111
- };
112
- recordStatus: {
113
- id: string;
114
- };
115
94
  };
116
95
  /**
117
96
  * Model persistent observable metadata.
118
97
  */
119
- metadata: Metadata;
98
+ metadata: S;
120
99
  /**
121
100
  * Model's persistent observable attributes.
122
101
  */
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("lodash"),s=require("@flumens/utils/dist/errors"),n=require("../Model.js"),i=require("./Media.js"),a=require("./Occurrence.js"),o=require("./helpers.js");function u(e,t){var r,s,n;t&&t.values?(e.id=t.values.id,e.samples&&t.samples&&(null===(r=e.samples)||void 0===r||r.forEach((function(e,r){return u(e,t.samples[r])}))),e.occurrences&&t.occurrences&&(null===(s=e.occurrences)||void 0===s||s.forEach((function(e,r){return u(e,t.occurrences[r])}))),e.media&&t.media&&(null===(n=e.media)||void 0===n||n.forEach((function(e,r){return u(e,t.media[r])})))):console.warn("Model didn't receive an id from the server")}var c=function(t){return e.__awaiter(void 0,void 0,void 0,(function(){var r,s,n;return e.__generator(this,(function(e){switch(e.label){case 0:return r=[],t.media?(s=function(e){return e.getFormData()},[4,Promise.all(t.media.map(s))]):[3,2];case 1:n=e.sent(),r.push.apply(r,n),e.label=2;case 2:return t.occurrences?[4,Promise.all(t.occurrences.map(c))]:[3,4];case 3:n=e.sent(),r.push.apply(r,n.flat()),e.label=4;case 4:return t.samples?[4,Promise.all(t.samples.map(c))]:[3,6];case 5:n=e.sent(),r.push.apply(r,n.flat()),e.label=6;case 6:return[2,r]}}))}))};function d(e,t){var r={values:{id:t||-1}};return e.occurrences&&(r.occurrences=e.occurrences.map((function(e){return d(e)}))),e.samples&&(r.samples=e.samples.map((function(e){return d(e)}))),e.media&&(r.media=e.media.map((function(e){return d(e)}))),r}function l(e){try{console.warn(JSON.stringify(e).substring(0,1e5))}catch(e){}}var h=function(n){function h(r){var s=this;void 0===r&&(r={});var i=r.metadata,a=void 0===i?{}:i,u=r.samples,c=void 0===u?[]:u,d=r.occurrences,l=void 0===d?[]:d,m=r.media,p=void 0===m?[]:m,f=r.attrs,v=void 0===f?{}:f,_=e.__rest(r,["metadata","samples","occurrences","media","attrs"]);(s=n.call(this,e.__assign(e.__assign({},_),{attrs:e.__assign({date:(new Date).toISOString(),location_type:"latlon"},v)}))||this).remote=t.observable({synchronising:!1,url:null,headers:{},timeout:12e4}),s.validateRemote=o.validateRemoteModel,s.error=t.observable({message:""}),s.debouncedValue=300,s.keys=function(){return e.__assign(e.__assign({},h.keys),function(t){return Object.keys(t).reduce((function(r,s){var n;return e.__assign(e.__assign({},r),((n={})[s]=t[s].remote||t[s],n))}),{})}(s.getSurvey().attrs||{}))},s.requiresRemoteSync=function(){return!s.syncedAt||s.updatedAt>s.syncedAt},s.metadata=t.observable(a),s.samples=t.observable(c),s.occurrences=t.observable(l),s.media=t.observable(p);var y=function(e){return e.parent=s};s.samples.forEach(y),s.occurrences.forEach(y),s.media.forEach(y);var g=function(e){var t;return(null===(t=e.added)||void 0===t?void 0:t.length)?(e.added.forEach(y),s.setupdatedAtTimestamp(Date.now())):e.removedCount&&s.setupdatedAtTimestamp(Date.now()),e};return t.intercept(s.samples,g),t.intercept(s.occurrences,g),t.intercept(s.media,g),s}return e.__extends(h,n),h.fromJSON=function(t,r,s,n){var o,u,c,d,l,h;return void 0===r&&(r=a.default),void 0===s&&(s=this),void 0===n&&(n=i.default),new this(e.__assign(e.__assign({},t),{createdAt:t.createdAt||(null===(o=t.metadata)||void 0===o?void 0:o.createdOn),updatedAt:t.updatedAt||(null===(u=t.metadata)||void 0===u?void 0:u.updatedOn),syncedAt:t.syncedAt||(null===(c=t.metadata)||void 0===c?void 0:c.syncedOn),samples:null===(d=t.samples)||void 0===d?void 0:d.map((function(e){return s.fromJSON(e,r,s,n)})),occurrences:null===(l=t.occurrences)||void 0===l?void 0:l.map((function(e){return r.fromJSON(e,n)})),media:null===(h=t.media)||void 0===h?void 0:h.map((function(e){return n.fromJSON(e)}))}))},h.prototype.setupdatedAtTimestamp=function(e){var t;n.prototype.setUpdatedAtTimestamp.call(this,e),null===(t=this.parent)||void 0===t||t.setupdatedAtTimestamp(e)},h.prototype.toJSON=function(){var r,s,i=n.prototype.toJSON.call(this);return JSON.parse(JSON.stringify(e.__assign(e.__assign({},i),{occurrences:this.occurrences.map((function(e){return e.toJSON()}))||[],samples:(null===(r=this.samples)||void 0===r?void 0:r.map((function(e){return e.toJSON()})))||[],media:(null===(s=this.media)||void 0===s?void 0:s.map((function(e){return e.toJSON()})))||[],metadata:t.toJS(this.metadata)||{}})))},h.prototype.getSurvey=function(){return this.survey?this.parent?this.parent.getSurvey().smp||{}:this.survey:{}},h.prototype.save=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.label){case 0:if(this.attrs.deleted)return[2];if(this.parent)return this.parent.save(),[2];if(!this._store)throw new Error("Trying to sync locally without a store");return[4,this._store.save(this.toJSON())];case 1:return e.sent(),[2]}}))}))},h.prototype.destroy=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s=this;return e.__generator(this,(function(e){switch(e.label){case 0:return r=function(){return Promise.all([Promise.all(s.media.map((function(e){return e.destroy(!0)}))),Promise.all(s.occurrences.map((function(e){return e.destroy(!0)})))])},this.parent?(this.parent.samples.remove(this),[4,r()]):[3,2];case 1:return e.sent(),t?[2]:(this.parent.save(),[2]);case 2:if(!this._store)throw new Error("Trying to sync locally without a store");return[4,this._store.destroy(this.cid)];case 3:return e.sent(),this.collection&&this.collection.remove(this),[4,r()];case 4:return e.sent(),this.attrs.deleted=!0,[2]}}))}))},h.prototype.sync=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,this.parent?this.parent.sync():n.prototype.sync.call(this)]}))}))},h.prototype.saveRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,n,i,a;return e.__generator(this,(function(e){switch(e.label){case 0:if(e.trys.push([0,6,,7]),!this.remote.url)throw new Error('A "remote" property is not configured.');t=void 0,e.label=1;case 1:return e.trys.push([1,4,,5]),this.remote.synchronising=!0,[4,this._uploadMedia()];case 2:return r=e.sent(),t=this.getSubmission(r),[4,this._createRemote(t)];case 3:return s=e.sent(),this.remote.synchronising=!1,u(this,s),n=(new Date).getTime(),this.updatedAt=n,this.syncedAt=n,this.save(),[3,5];case 4:throw i=e.sent(),this.remote.synchronising=!1,i.payload=t,i;case 5:return[3,7];case 6:throw 400===(a=e.sent()).status&&a.payload&&l(a.payload),a;case 7:return[2]}}))}))},h.prototype.updateRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,n,i,a;return e.__generator(this,(function(e){switch(e.label){case 0:if(e.trys.push([0,5,,6]),!this.remote.url)throw new Error('A "remote" property is not configured.');t=void 0,e.label=1;case 1:return e.trys.push([1,3,,4]),this.remote.synchronising=!0,r={},t=this.getSubmission(r),[4,this._updateRemote(this.id,t)];case 2:return s=e.sent(),this.remote.synchronising=!1,u(this,s),n=(new Date).getTime(),this.updatedAt=n,this.syncedAt=n,this.save(),[3,4];case 3:throw i=e.sent(),this.remote.synchronising=!1,i.payload=t,i;case 4:return[3,6];case 5:throw 400===(a=e.sent()).status&&a.payload&&l(a.payload),a;case 6:return[2]}}))}))},h.prototype._createRemote=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,n,i,a;return e.__generator(this,(function(e){switch(e.label){case 0:return r=this.remote.url,"function"!=typeof this.remote.headers?[3,2]:[4,this.remote.headers()];case 1:return n=e.sent(),[3,3];case 2:n=this.remote.headers,e.label=3;case 3:i={method:"POST",headers:n,body:JSON.stringify(t)},e.label=4;case 4:return e.trys.push([4,6,,7]),[4,o.makeRequest("".concat(r,"/samples"),i)];case 5:return[2,e.sent()];case 6:if(409===(a=e.sent()).status&&a.res&&a.res.duplicate_of)return[2,d(this,a.res.duplicate_of.id)];if("timeout"===a.message)throw new s.HandledError("Request aborted because of a network issue (timeout or similar).");throw a;case 7:return[2]}}))}))},h.prototype._updateRemote=function(t,r){return e.__awaiter(this,void 0,void 0,(function(){var n,i,a,u;return e.__generator(this,(function(e){switch(e.label){case 0:return n=this.remote.url,"function"!=typeof this.remote.headers?[3,2]:[4,this.remote.headers()];case 1:return i=e.sent(),[3,3];case 2:i=this.remote.headers,e.label=3;case 3:a={method:"PUT",headers:i,body:JSON.stringify(r)},e.label=4;case 4:return e.trys.push([4,6,,7]),[4,o.makeRequest("".concat(n,"/samples/").concat(t),a)];case 5:return[2,e.sent()];case 6:if(409===(u=e.sent()).status&&u.res&&u.res.duplicate_of)return[2,d(this,u.res.duplicate_of.id)];if("timeout"===u.message)throw new s.HandledError("Request aborted because of a network issue (timeout or similar).");throw u;case 7:return[2]}}))}))},h.prototype._uploadMedia=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,n,i,a,u,d=this;return e.__generator(this,(function(l){switch(l.label){case 0:return t={},[4,c(this)];case 1:if(r=l.sent(),!r.length)return[2,t];n=function(t){return e.__awaiter(d,void 0,void 0,(function(){var r,n,i;return e.__generator(this,(function(e){switch(e.label){case 0:return r=this.remote.url,"function"!=typeof this.remote.headers?[3,2]:[4,this.remote.headers()];case 1:return n=e.sent(),[3,3];case 2:n=this.remote.headers,e.label=3;case 3:i={method:"POST",headers:n,body:t};try{return[2,o.makeRequest("".concat(r,"/media-queue"),i)]}catch(e){if("timeout"===e.message)throw new s.HandledError("Request aborted because of a network issue (timeout or similar).");throw e}return[2]}}))}))},i=5,a=function(s){var a,o,u;return e.__generator(this,(function(c){switch(c.label){case 0:return a=r.slice(s,s+i),o=new FormData,a.forEach((function(e){return o.append.apply(o,e)})),[4,n(o)];case 1:return u=c.sent(),t=e.__assign(e.__assign({},t),u),[2]}}))},u=0,l.label=2;case 2:return u<r.length?[5,a(u)]:[3,5];case 3:l.sent(),l.label=4;case 4:return u+=i,[3,2];case 5:return[2,t]}}))}))},h.prototype.getSubmission=function(t){var s=this;void 0===t&&(t={});var n="function"==typeof this.keys?this.keys():this.keys,i=e.__assign(e.__assign({},h.keys),n),a={values:{external_key:this.cid},media:[],samples:[],occurrences:[]};this.id&&(a.values.id=this.id);var o=function(e,t){var r=i[e].values;if(!r)return t;if("function"==typeof r)return r(t,a,s);if(t instanceof Array)return t.map((function(t){return o(e,t)}));if(r instanceof Array){var n=r.find((function(e){return e.value===t}));if(!n||!n.id)throw new Error('A "'.concat(e,'" attribute "').concat(t,'" value could not be mapped to a remote database field.'));return n.id}return r[t]};Object.keys(this.attrs).forEach((function(e){var t=s.attrs[e],n=function(e){return null==e};if(!n(t)){if(!i[e])return e=e.includes("smpAttr:")?e:r.snakeCase(e),void(a.values[e]=t);if(!n(t=o(e,t))){var u=i[e].id||e,c=Number.isNaN(Number(u))?u:"smpAttr:".concat(u);c=c.includes("smpAttr:")?c:r.snakeCase(c),a.values[c]=t}}})),this.samples.forEach((function(e){s.attrs.training&&(e.attrs.training=s.attrs.training);var r=e.getSubmission(t);r&&a.samples.push(r)})),this.occurrences.forEach((function(e){s.attrs.training&&(e.attrs.training=s.attrs.training);var r=e.getSubmission(t);r&&a.occurrences.push(r)})),this.media.forEach((function(e){var r=e.getSubmission(t);r&&a.media.push(r)}));var u=this.getSurvey();return u.modifySubmission?u.modifySubmission(a,this):a},h.prototype.isUploaded=function(){return this.parent?this.parent.isUploaded():!!this.syncedAt},h.prototype.isDisabled=function(){return this.isUploaded()},h.keys={surveyId:{id:"survey_id"},date:{id:"date"},sample_method_id:{id:"sample_method_id"},location:{id:"entered_sref"},location_type:{id:"entered_sref_system",values:{british:"OSGB",irish:"OSIE",channel:"utm30ed50",latlon:4326}},inputForm:{id:"input_form"},group:{id:"group_id"},comment:{id:"comment"},training:{id:"training",values:o.boolToWarehouseValue},deleted:{id:"deleted",values:o.boolToWarehouseValue},privacyPrecision:{id:"privacy_precision"},recordStatus:{id:"record_status"}},h}(n.default);exports._getMediaFormData=c,exports.default=h;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("lodash"),s=require("@flumens/utils/dist/errors"),n=require("../Model.js"),a=require("./Media.js"),i=require("./Occurrence.js"),o=require("./helpers.js");function u(e,t){var r,s,n;t&&t.values?(e.id=t.values.id,e.samples&&t.samples&&(null===(r=e.samples)||void 0===r||r.forEach((function(e,r){return u(e,t.samples[r])}))),e.occurrences&&t.occurrences&&(null===(s=e.occurrences)||void 0===s||s.forEach((function(e,r){return u(e,t.occurrences[r])}))),e.media&&t.media&&(null===(n=e.media)||void 0===n||n.forEach((function(e,r){return u(e,t.media[r])})))):console.warn("Model didn't receive an id from the server")}var c=function(t){return e.__awaiter(void 0,void 0,void 0,(function(){var r,s,n;return e.__generator(this,(function(e){switch(e.label){case 0:return r=[],t.media?(s=function(e){return e.getFormData()},[4,Promise.all(t.media.map(s))]):[3,2];case 1:n=e.sent(),r.push.apply(r,n),e.label=2;case 2:return t.occurrences?[4,Promise.all(t.occurrences.map(c))]:[3,4];case 3:n=e.sent(),r.push.apply(r,n.flat()),e.label=4;case 4:return t.samples?[4,Promise.all(t.samples.map(c))]:[3,6];case 5:n=e.sent(),r.push.apply(r,n.flat()),e.label=6;case 6:return[2,r]}}))}))};function d(e,t){var r={values:{id:t||-1}};return e.occurrences&&(r.occurrences=e.occurrences.map((function(e){return d(e)}))),e.samples&&(r.samples=e.samples.map((function(e){return d(e)}))),e.media&&(r.media=e.media.map((function(e){return d(e)}))),r}function l(e){try{console.warn(JSON.stringify(e).substring(0,1e5))}catch(e){}}var h=function(n){function h(r){var s=this;void 0===r&&(r={});var a=r.metadata,i=void 0===a?{}:a,u=r.samples,c=void 0===u?[]:u,d=r.occurrences,l=void 0===d?[]:d,m=r.media,p=void 0===m?[]:m,f=r.attrs,v=void 0===f?{}:f,_=e.__rest(r,["metadata","samples","occurrences","media","attrs"]);(s=n.call(this,e.__assign(e.__assign({},_),{attrs:e.__assign({date:(new Date).toISOString(),location_type:"latlon"},v)}))||this).remote=t.observable({synchronising:!1,url:null,headers:{},timeout:12e4}),s.validateRemote=o.validateRemoteModel,s.error=t.observable({message:""}),s.debouncedValue=300,s.keys=function(){return e.__assign(e.__assign({},h.keys),function(t){return Object.keys(t).reduce((function(r,s){var n;return e.__assign(e.__assign({},r),((n={})[s]=t[s].remote||t[s],n))}),{})}(s.getSurvey().attrs||{}))},s.requiresRemoteSync=function(){return!s.syncedAt||s.updatedAt>s.syncedAt},s.metadata=t.observable(i),s.samples=t.observable(c),s.occurrences=t.observable(l),s.media=t.observable(p);var y=function(e){return e.parent=s};s.samples.forEach(y),s.occurrences.forEach(y),s.media.forEach(y);var g=function(e){var t;return(null===(t=e.added)||void 0===t?void 0:t.length)?(e.added.forEach(y),s.setupdatedAtTimestamp(Date.now())):e.removedCount&&s.setupdatedAtTimestamp(Date.now()),e};return t.intercept(s.samples,g),t.intercept(s.occurrences,g),t.intercept(s.media,g),s}return e.__extends(h,n),h.fromJSON=function(t,r,s,n){var o,u,c,d,l,h,m;void 0===r&&(r=i.default),void 0===s&&(s=this),void 0===n&&(n=a.default);var p=(null===(o=null==t?void 0:t.attrs)||void 0===o?void 0:o.attrs)?null==t?void 0:t.attrs:t;return new this(e.__assign(e.__assign({},t),{attrs:p.attrs,metadata:p.metadata,createdAt:t.createdAt||(null===(u=t.metadata)||void 0===u?void 0:u.createdOn),updatedAt:t.updatedAt||(null===(c=t.metadata)||void 0===c?void 0:c.updatedOn),syncedAt:t.syncedAt||(null===(d=t.metadata)||void 0===d?void 0:d.syncedOn),samples:null===(l=p.samples)||void 0===l?void 0:l.map((function(e){return s.fromJSON(e,r,s,n)})),occurrences:null===(h=p.occurrences)||void 0===h?void 0:h.map((function(e){return r.fromJSON(e,n)})),media:null===(m=p.media)||void 0===m?void 0:m.map((function(e){return n.fromJSON(e)}))}))},h.prototype.setupdatedAtTimestamp=function(e){var t;n.prototype.setUpdatedAtTimestamp.call(this,e),null===(t=this.parent)||void 0===t||t.setupdatedAtTimestamp(e)},h.prototype.toJSON=function(){var r,s,a,i,o=n.prototype.toJSON.call(this);return this.parent?JSON.parse(JSON.stringify(e.__assign(e.__assign({},o),{metadata:t.toJS(this.metadata)||{},occurrences:this.occurrences.map((function(e){return e.toJSON()}))||[],samples:(null===(a=this.samples)||void 0===a?void 0:a.map((function(e){return e.toJSON()})))||[],media:(null===(i=this.media)||void 0===i?void 0:i.map((function(e){return e.toJSON()})))||[]}))):JSON.parse(JSON.stringify(e.__assign(e.__assign({},o),{attrs:{attrs:o.attrs,metadata:t.toJS(this.metadata)||{},occurrences:this.occurrences.map((function(e){return e.toJSON()}))||[],samples:(null===(r=this.samples)||void 0===r?void 0:r.map((function(e){return e.toJSON()})))||[],media:(null===(s=this.media)||void 0===s?void 0:s.map((function(e){return e.toJSON()})))||[]}})))},h.prototype.getSurvey=function(){return this.survey?this.parent?this.parent.getSurvey().smp||{}:this.survey:{}},h.prototype.save=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.label){case 0:if(this.attrs.deleted)return[2];if(this.parent)return this.parent.save(),[2];if(!this._store)throw new Error("Trying to sync locally without a store");return[4,this._store.save(this.toJSON())];case 1:return e.sent(),[2]}}))}))},h.prototype.destroy=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s=this;return e.__generator(this,(function(e){switch(e.label){case 0:return r=function(){return Promise.all([Promise.all(s.media.map((function(e){return e.destroy(!0)}))),Promise.all(s.occurrences.map((function(e){return e.destroy(!0)})))])},this.parent?(this.parent.samples.remove(this),[4,r()]):[3,2];case 1:return e.sent(),t?[2]:(this.parent.save(),[2]);case 2:if(!this._store)throw new Error("Trying to sync locally without a store");return[4,this._store.destroy(this.cid)];case 3:return e.sent(),this.collection&&this.collection.remove(this),[4,r()];case 4:return e.sent(),this.attrs.deleted=!0,[2]}}))}))},h.prototype.sync=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,this.parent?this.parent.sync():n.prototype.sync.call(this)]}))}))},h.prototype.saveRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,n,a,i;return e.__generator(this,(function(e){switch(e.label){case 0:if(e.trys.push([0,6,,7]),!this.remote.url)throw new Error('A "remote" property is not configured.');t=void 0,e.label=1;case 1:return e.trys.push([1,4,,5]),this.remote.synchronising=!0,[4,this._uploadMedia()];case 2:return r=e.sent(),t=this.getSubmission(r),[4,this._createRemote(t)];case 3:return s=e.sent(),this.remote.synchronising=!1,u(this,s),n=(new Date).getTime(),this.updatedAt=n,this.syncedAt=n,this.save(),[3,5];case 4:throw a=e.sent(),this.remote.synchronising=!1,a.payload=t,a;case 5:return[3,7];case 6:throw 400===(i=e.sent()).status&&i.payload&&l(i.payload),i;case 7:return[2]}}))}))},h.prototype.updateRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,n,a,i;return e.__generator(this,(function(e){switch(e.label){case 0:if(e.trys.push([0,5,,6]),!this.remote.url)throw new Error('A "remote" property is not configured.');t=void 0,e.label=1;case 1:return e.trys.push([1,3,,4]),this.remote.synchronising=!0,r={},t=this.getSubmission(r),[4,this._updateRemote(this.id,t)];case 2:return s=e.sent(),this.remote.synchronising=!1,u(this,s),n=(new Date).getTime(),this.updatedAt=n,this.syncedAt=n,this.save(),[3,4];case 3:throw a=e.sent(),this.remote.synchronising=!1,a.payload=t,a;case 4:return[3,6];case 5:throw 400===(i=e.sent()).status&&i.payload&&l(i.payload),i;case 6:return[2]}}))}))},h.prototype._createRemote=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,n,a,i;return e.__generator(this,(function(e){switch(e.label){case 0:return r=this.remote.url,"function"!=typeof this.remote.headers?[3,2]:[4,this.remote.headers()];case 1:return n=e.sent(),[3,3];case 2:n=this.remote.headers,e.label=3;case 3:a={method:"POST",headers:n,body:JSON.stringify(t)},e.label=4;case 4:return e.trys.push([4,6,,7]),[4,o.makeRequest("".concat(r,"/samples"),a)];case 5:return[2,e.sent()];case 6:if(409===(i=e.sent()).status&&i.res&&i.res.duplicate_of)return[2,d(this,i.res.duplicate_of.id)];if("timeout"===i.message)throw new s.HandledError("Request aborted because of a network issue (timeout or similar).");throw i;case 7:return[2]}}))}))},h.prototype._updateRemote=function(t,r){return e.__awaiter(this,void 0,void 0,(function(){var n,a,i,u;return e.__generator(this,(function(e){switch(e.label){case 0:return n=this.remote.url,"function"!=typeof this.remote.headers?[3,2]:[4,this.remote.headers()];case 1:return a=e.sent(),[3,3];case 2:a=this.remote.headers,e.label=3;case 3:i={method:"PUT",headers:a,body:JSON.stringify(r)},e.label=4;case 4:return e.trys.push([4,6,,7]),[4,o.makeRequest("".concat(n,"/samples/").concat(t),i)];case 5:return[2,e.sent()];case 6:if(409===(u=e.sent()).status&&u.res&&u.res.duplicate_of)return[2,d(this,u.res.duplicate_of.id)];if("timeout"===u.message)throw new s.HandledError("Request aborted because of a network issue (timeout or similar).");throw u;case 7:return[2]}}))}))},h.prototype._uploadMedia=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,n,a,i,u,d=this;return e.__generator(this,(function(l){switch(l.label){case 0:return t={},[4,c(this)];case 1:if(r=l.sent(),!r.length)return[2,t];n=function(t){return e.__awaiter(d,void 0,void 0,(function(){var r,n,a;return e.__generator(this,(function(e){switch(e.label){case 0:return r=this.remote.url,"function"!=typeof this.remote.headers?[3,2]:[4,this.remote.headers()];case 1:return n=e.sent(),[3,3];case 2:n=this.remote.headers,e.label=3;case 3:a={method:"POST",headers:n,body:t};try{return[2,o.makeRequest("".concat(r,"/media-queue"),a)]}catch(e){if("timeout"===e.message)throw new s.HandledError("Request aborted because of a network issue (timeout or similar).");throw e}return[2]}}))}))},a=5,i=function(s){var i,o,u;return e.__generator(this,(function(c){switch(c.label){case 0:return i=r.slice(s,s+a),o=new FormData,i.forEach((function(e){return o.append.apply(o,e)})),[4,n(o)];case 1:return u=c.sent(),t=e.__assign(e.__assign({},t),u),[2]}}))},u=0,l.label=2;case 2:return u<r.length?[5,i(u)]:[3,5];case 3:l.sent(),l.label=4;case 4:return u+=a,[3,2];case 5:return[2,t]}}))}))},h.prototype.getSubmission=function(t){var s=this;void 0===t&&(t={});var n="function"==typeof this.keys?this.keys():this.keys,a=e.__assign(e.__assign({},h.keys),n),i={values:{external_key:this.cid},media:[],samples:[],occurrences:[]};this.id&&(i.values.id=this.id);var o=function(e,t){var r=a[e].values;if(!r)return t;if("function"==typeof r)return r(t,i,s);if(t instanceof Array)return t.map((function(t){return o(e,t)}));if(r instanceof Array){var n=r.find((function(e){return e.value===t}));if(!n||!n.id)throw new Error('A "'.concat(e,'" attribute "').concat(t,'" value could not be mapped to a remote database field.'));return n.id}return r[t]};Object.keys(this.attrs).forEach((function(e){var t=s.attrs[e],n=function(e){return null==e};if(!n(t)){if(!a[e])return e=e.includes("smpAttr:")?e:r.snakeCase(e),void(i.values[e]=t);if(!n(t=o(e,t))){var u=a[e].id||e,c=Number.isNaN(Number(u))?u:"smpAttr:".concat(u);c=c.includes("smpAttr:")?c:r.snakeCase(c),i.values[c]=t}}})),this.samples.forEach((function(e){s.attrs.training&&(e.attrs.training=s.attrs.training);var r=e.getSubmission(t);r&&i.samples.push(r)})),this.occurrences.forEach((function(e){s.attrs.training&&(e.attrs.training=s.attrs.training);var r=e.getSubmission(t);r&&i.occurrences.push(r)})),this.media.forEach((function(e){var r=e.getSubmission(t);r&&i.media.push(r)}));var u=this.getSurvey();return u.modifySubmission?u.modifySubmission(i,this):i},h.prototype.isUploaded=function(){return this.parent?this.parent.isUploaded():!!this.syncedAt},h.prototype.isDisabled=function(){return this.isUploaded()},h.keys={location:{id:"entered_sref"},location_type:{id:"entered_sref_system",values:{british:"OSGB",irish:"OSIE",channel:"utm30ed50",latlon:4326}},group:{id:"group_id"},training:{id:"training",values:o.boolToWarehouseValue},deleted:{id:"deleted",values:o.boolToWarehouseValue}},h}(n.default);exports._getMediaFormData=c,exports.default=h;
package/dist/Model.d.ts CHANGED
@@ -48,7 +48,7 @@ export default class Model {
48
48
  */
49
49
  protected _store?: Store;
50
50
  /**
51
- * A promise to flag if the model was initialised from the store.
51
+ * A deferred promise to flag if the model was initialised from the store.
52
52
  */
53
53
  ready?: Promise<boolean>;
54
54
  protected debouncedValue: number;
@@ -57,7 +57,8 @@ export default class Model {
57
57
  /**
58
58
  * Initialize the model from store.
59
59
  */
60
- private _fromStore;
60
+ fetch(): Promise<boolean>;
61
+ private _fetch;
61
62
  /**
62
63
  * Save the model to the offline store.
63
64
  */
package/dist/Model.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),r=require("mobx-utils");function s(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var i=s(require("@flumens/utils/dist/uuid")),n={deleted:!1},o=function(){function s(s){var o=this,a=s.id,u=void 0===a?"":a,d=s.cid,c=void 0===d?"":d,h=s.createdAt,f=s.updatedAt,_=s.syncedAt,l=s.attrs,p=void 0===l?{}:l,v=s.store;this.debouncedValue=3e3,this.id=u,this.cid=c||u||i.default();var y,A,b=Date.now();this.createdAt=h||b,this.updatedAt=f||b,this.syncedAt=_,this.attrs=e.observable((y=t.__assign(t.__assign({},n),p),JSON.parse(JSON.stringify(y)))),this._store=v,this.ready=this._fromStore();var w=function(){o.updatedAt=Date.now(),function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];clearTimeout(A),A=setTimeout((function(){return o.sync.apply(o,t)}),o.debouncedValue)}()};this.ready.then((function(){return r.deepObserve(o.attrs,w)}))}return s.prototype.setUpdatedAtTimestamp=function(t){this.updatedAt=t},s.prototype._fromStore=function(){return t.__awaiter(this,void 0,void 0,(function(){var r;return t.__generator(this,(function(t){switch(t.label){case 0:return this._store?[4,this._store.find(this.cid)]:[2,!1];case 1:return(r=t.sent())?[3,3]:[4,this.save()];case 2:return t.sent(),[2,!0];case 3:return r.id&&(this.id=r.id),r.cid&&(this.cid=r.cid),this.createdAt=r.createdAt,this.updatedAt=r.updatedAt,this.syncedAt=r.syncedAt,e.set(this.attrs,r.attrs),[2,!0]}}))}))},s.prototype.save=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:if(!this._store)throw new Error("Trying to save locally without a store");return[4,this._store.save(this.toJSON())];case 1:return t.sent(),[2]}}))}))},s.prototype.destroy=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:if(!this._store)throw new Error("Trying to delete locally without a store");return[4,this._store.destroy(this.cid)];case 1:return t.sent(),[2]}}))}))},s.prototype.sync=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:return this._store?[4,this.save()]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}}))}))},s.prototype.toJSON=function(){return{id:this.id,cid:this.cid,createdAt:this.createdAt,updatedAt:this.updatedAt,syncedAt:this.syncedAt,attrs:e.toJS(this.attrs)}},s.prototype.resetDefaults=function(r){var s=this;this.id="";var i=JSON.parse(JSON.stringify(t.__assign(t.__assign({},n),r)));e.set(this.attrs,i);var o=Object.keys(i);return Object.keys(this.attrs).forEach((function(t){o.includes(t)||(s.attrs[t]=null,delete s.attrs[t])})),this.save()},s.extendAttrs=function(r,s){return e.set(r,t.__assign(t.__assign({},s),r)),r},s}();exports.default=o;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),r=require("mobx-utils");function i(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var s=i(require("@flumens/utils/dist/uuid")),n={deleted:!1},o=function(){function i(i){var o=this,a=i.id,u=void 0===a?"":a,d=i.cid,c=void 0===d?"":d,h=i.createdAt,f=i.updatedAt,_=i.syncedAt,l=i.attrs,p=void 0===l?{}:l,v=i.store;this.debouncedValue=3e3,this.id=u,this.cid=c||u||s.default();var y,A,b=Date.now();this.createdAt=h||b,this.updatedAt=f||b,this.syncedAt=_,this.attrs=e.observable((y=t.__assign(t.__assign({},n),p),JSON.parse(JSON.stringify(y)))),this._store=v;r.deepObserve(this.attrs,(function(){o.updatedAt=Date.now(),function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];clearTimeout(A),A=setTimeout((function(){return o.sync.apply(o,t)}),o.debouncedValue)}()}))}return i.prototype.setUpdatedAtTimestamp=function(t){this.updatedAt=t},i.prototype.fetch=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){return this.ready=this._fetch(),[2,this.ready]}))}))},i.prototype._fetch=function(){return t.__awaiter(this,void 0,void 0,(function(){var r;return t.__generator(this,(function(t){switch(t.label){case 0:return this._store?[4,this._store.find(this.cid)]:[2,!1];case 1:return(r=t.sent())?[3,3]:[4,this.save()];case 2:return t.sent(),[2,!0];case 3:return r.id&&(this.id=r.id),r.cid&&(this.cid=r.cid),e.set(this.attrs,r.attrs),this.createdAt=r.createdAt,this.updatedAt=r.updatedAt,this.syncedAt=r.syncedAt,[2,!0]}}))}))},i.prototype.save=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:if(!this._store)throw new Error("Trying to save locally without a store");return[4,this._store.save(this.toJSON())];case 1:return t.sent(),[2]}}))}))},i.prototype.destroy=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:if(!this._store)throw new Error("Trying to delete locally without a store");return[4,this._store.destroy(this.cid)];case 1:return t.sent(),[2]}}))}))},i.prototype.sync=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:return this._store?[4,this.save()]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}}))}))},i.prototype.toJSON=function(){return{id:this.id,cid:this.cid,createdAt:this.createdAt,updatedAt:this.updatedAt,syncedAt:this.syncedAt,attrs:e.toJS(this.attrs)}},i.prototype.resetDefaults=function(r){var i=this;this.id="";var s=JSON.parse(JSON.stringify(t.__assign(t.__assign({},n),r)));e.set(this.attrs,s);var o=Object.keys(s);return Object.keys(this.attrs).forEach((function(t){o.includes(t)||(i.attrs[t]=null,delete i.attrs[t])})),this.save()},i.extendAttrs=function(r,i){return e.set(r,t.__assign(t.__assign({},i),r)),r},i}();exports.default=o;
@@ -3,6 +3,7 @@ export default class LocalForageStore implements Store {
3
3
  debugging: any;
4
4
  localForage: any;
5
5
  ready: any;
6
+ storeName: any;
6
7
  constructor(options: any);
7
8
  static _getDriverOrder(driverOrder: any): any;
8
9
  save(val: ModelDTO): Promise<any>;
@@ -18,5 +19,4 @@ export default class LocalForageStore implements Store {
18
19
  * Imports objects to store.
19
20
  */
20
21
  import(obj: any): Promise<void>;
21
- _printDiff(key: any, val: any): Promise<void>;
22
22
  }
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),r=require("deep-diff"),t=require("localforage"),n=require("localforage-cordovasqlitedriver"),i=require("lodash"),o=require("@ionic/react");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=a(t),c=a(n),u=["indexeddb","websql","localstorage"];if(o.isPlatform("hybrid")){if(!window.sqlitePlugin)throw new Error("cordova-sql-storage plugin is missing. Please install it.");u=e.__spreadArray([c.default],u,!0)}var l={driverOrder:u},d=function(){function t(r){var n=this,i=e.__assign(e.__assign({},l),r);this.debugging=i.debugging,this.localForage=null,this.ready=new Promise((function(e,r){var o=new Promise((function(e){i.driverOrder&&"object"==typeof i.driverOrder[0]?s.default.defineDriver(i.driverOrder[0]).then(e):e(void 0)}));if(!i.storeName)throw new Error("storeName prop is missing");o.then((function(){var o={name:i.name||"indicia",storeName:i.storeName};i.version&&(o.version=i.version);var a=t._getDriverOrder(i.driverOrder),c=i.LocalForage||s.default;n.localForage=c.createInstance(o),n.localForage.setDriver(a).then(e).catch(r)}))}))}return t._getDriverOrder=function(e){return e.map((function(e){switch(e){case"indexeddb":return s.default.INDEXEDDB;case"websql":return s.default.WEBSQL;case"localstorage":return s.default.LOCALSTORAGE;default:return"object"==typeof e&&e._driver?e._driver:console.error("No such db driver!")}}))},t.prototype.save=function(r){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:if(e.sent(),!r.cid)throw new Error("Invalid key passed to store");return this.debugging&&this._printDiff(r.cid,r),[2,this.localForage.setItem(r.cid,r)]}}))}))},t.prototype.find=function(r){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:if(e.sent(),!r)throw new Error("Invalid key passed to store");return[2,this.localForage.getItem(r)]}}))}))},t.prototype.findAll=function(){return e.__awaiter(this,void 0,void 0,(function(){var r;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:return e.sent(),r=[],[4,this.localForage.iterate((function(e){r.push(e)}))];case 2:return e.sent(),[2,r]}}))}))},t.prototype.destroy=function(r){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:if(e.sent(),!r)throw new Error("Invalid key passed to store");return[2,this.localForage.removeItem(r)]}}))}))},t.prototype.destroyAll=function(){return e.__awaiter(this,void 0,void 0,(function(){var r,t=this;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:return e.sent(),[4,this.findAll()];case 2:return r=e.sent(),[4,Promise.all(r.map((function(e){return t.destroy(e)})))];case 3:return e.sent(),[2]}}))}))},t.prototype.export=function(){return e.__awaiter(this,void 0,void 0,(function(){var r;return e.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),r=function(r,t){var n;return e.__assign(e.__assign({},r),((n={})[t.cid]=t,n))},[4,this.findAll()];case 2:return[2,t.sent().reduce(r,{})]}}))}))},t.prototype.import=function(r){return e.__awaiter(this,void 0,void 0,(function(){var t,n=this;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:return e.sent(),[4,this.destroyAll()];case 2:if(e.sent(),"object"!=typeof r)throw new Error("Invalid obj passed to store");return t=Object.entries(r).map((function(e){var r=e[1];return n.save(r)})),[4,Promise.all(t)];case 3:return e.sent(),[2]}}))}))},t.prototype._printDiff=function(t,n){return e.__awaiter(this,void 0,void 0,(function(){var o,a,s,c,u,l,d;return e.__generator(this,(function(e){switch(e.label){case 0:return o=this.localForage._config.storeName,[4,this.localForage.getItem(t)];case 1:return a=e.sent(),(s=r.diff(a,n))?(c={},u=0,l="",s.forEach((function(e){var r,n,a=((r={})[o]=((n={})[t]={},n),r);if(!e.path)return a[o][t]=e.rhs,console.groupCollapsed("Δ + ".concat(t)),console.log(a),void console.groupEnd();e.path.reduce((function(r,t,n){if(e.path.length-1>n)return r[t]={},r[t];var i=JSON.stringify(e.lhs,null,2),o=JSON.stringify(e.rhs,null,2);if(i===o)return r[t];u++,r[t]="".concat(i," -> ").concat(o),l="".concat(t,": ").concat(i," -> ").concat(o)}),a[o][t]),c=i.merge(c,a)})),u&&(d="Δ ".concat(t),1===u&&(d+=" ".concat(l)),console.groupCollapsed(d),console.log(c),console.groupEnd()),[2]):[2]}}))}))},t}();exports.default=d;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),r=require("localforage"),t=require("localforage-cordovasqlitedriver"),i=require("@ionic/react"),n=require("./utils.js");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=o(r),a=o(t),u=["indexeddb","websql","localstorage"];if(i.isPlatform("hybrid")){if(!window.sqlitePlugin)throw new Error("cordova-sql-storage plugin is missing. Please install it.");u=e.__spreadArray([a.default],u,!0)}var c={driverOrder:u},d=function(){function r(t){var i=this,n=e.__assign(e.__assign({},c),t);this.debugging=n.debugging,this.localForage=null,this.ready=new Promise((function(e,t){var o=new Promise((function(e){n.driverOrder&&"object"==typeof n.driverOrder[0]?s.default.defineDriver(n.driverOrder[0]).then(e):e(void 0)}));if(!n.storeName)throw new Error("storeName prop is missing");i.storeName=n.storeName,o.then((function(){var o={name:n.name||"indicia",storeName:n.storeName};n.version&&(o.version=n.version);var a=r._getDriverOrder(n.driverOrder),u=n.LocalForage||s.default;i.localForage=u.createInstance(o),i.localForage.setDriver(a).then(e).catch(t)}))}))}return r._getDriverOrder=function(e){return e.map((function(e){switch(e){case"indexeddb":return s.default.INDEXEDDB;case"websql":return s.default.WEBSQL;case"localstorage":return s.default.LOCALSTORAGE;default:return"object"==typeof e&&e._driver?e._driver:console.error("No such db driver!")}}))},r.prototype.save=function(r){return e.__awaiter(this,void 0,void 0,(function(){var t;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:if(e.sent(),!r.cid)throw new Error("Invalid key passed to store");return this.debugging?[4,this.find(r.cid)]:[3,3];case 2:t=e.sent(),n.printDiff(t,r,r.cid,this.storeName),e.label=3;case 3:return[2,this.localForage.setItem(r.cid,r)]}}))}))},r.prototype.find=function(r){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:if(e.sent(),!r)throw new Error("Invalid key passed to store");return[2,this.localForage.getItem(r)]}}))}))},r.prototype.findAll=function(){return e.__awaiter(this,void 0,void 0,(function(){var r;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:return e.sent(),r=[],[4,this.localForage.iterate((function(e){r.push(e)}))];case 2:return e.sent(),[2,r]}}))}))},r.prototype.destroy=function(r){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:if(e.sent(),!r)throw new Error("Invalid key passed to store");return[2,this.localForage.removeItem(r)]}}))}))},r.prototype.destroyAll=function(){return e.__awaiter(this,void 0,void 0,(function(){var r,t=this;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:return e.sent(),[4,this.findAll()];case 2:return r=e.sent(),[4,Promise.all(r.map((function(e){return t.destroy(e)})))];case 3:return e.sent(),[2]}}))}))},r.prototype.export=function(){return e.__awaiter(this,void 0,void 0,(function(){var r;return e.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),r=function(r,t){var i;return e.__assign(e.__assign({},r),((i={})[t.cid]=t,i))},[4,this.findAll()];case 2:return[2,t.sent().reduce(r,{})]}}))}))},r.prototype.import=function(r){return e.__awaiter(this,void 0,void 0,(function(){var t,i=this;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:return e.sent(),[4,this.destroyAll()];case 2:if(e.sent(),"object"!=typeof r)throw new Error("Invalid obj passed to store");return t=Object.entries(r).map((function(e){var r=e[1];return i.save(r)})),[4,Promise.all(t)];case 3:return e.sent(),[2]}}))}))},r}();exports.default=d;
@@ -1,10 +1,21 @@
1
+ import Deferred from '@flumens/utils/dist/deferred';
2
+ type SQLiteDatabaseOptions = {
3
+ name?: string;
4
+ debug?: boolean;
5
+ web?: boolean;
6
+ };
1
7
  export default class SQLiteDatabase {
8
+ static migrateCordova(): Promise<void>;
2
9
  private sqliteConnection;
3
10
  private connection?;
4
11
  private get db();
5
12
  protected name: string;
6
- protected debugging: boolean;
7
- constructor(databaseName?: string, debugging?: boolean);
13
+ protected debug: boolean;
14
+ protected isWeb: boolean;
15
+ ready: Deferred<boolean>;
16
+ constructor({ name, debug, web }: SQLiteDatabaseOptions);
8
17
  init(): Promise<void>;
9
- query(query: string, values?: any[]): Promise<import("@capacitor-community/sqlite").DBSQLiteValues | undefined>;
18
+ query<T>(query: string, values?: any[]): Promise<T[]>;
19
+ getUrl(): Promise<string | undefined>;
10
20
  }
21
+ export {};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("@capacitor-community/sqlite"),n=require("@ionic/core"),i=function(){function i(e,n){this.sqliteConnection=new t.SQLiteConnection(t.CapacitorSQLite),this.name="main",this.debugging=!1,this.name=e||this.name,this.debugging=n||this.debugging}return Object.defineProperty(i.prototype,"db",{get:function(){return this.connection},enumerable:!1,configurable:!0}),i.prototype.init=function(){return e.__awaiter(this,void 0,void 0,(function(){var t;return e.__generator(this,(function(e){switch(e.label){case 0:return n.isPlatform("hybrid")?[3,3]:[4,customElements.whenDefined("jeep-sqlite")];case 1:return e.sent(),[4,this.sqliteConnection.initWebStore()];case 2:e.sent(),e.label=3;case 3:return t=this,[4,this.sqliteConnection.createConnection("".concat(this.name,"."),!1,"no-encryption",1,!1)];case 4:return t.connection=e.sent(),[4,this.connection.open()];case 5:return e.sent(),[2]}}))}))},i.prototype.query=function(t,n){var i,o;return e.__awaiter(this,void 0,void 0,(function(){var r;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,null===(i=this.db)||void 0===i?void 0:i.query(t,n)];case 1:return r=e.sent(),this.debugging?(console.groupCollapsed("💾 SQL: ".concat(t.trimStart().replaceAll(/\n/g," ").replaceAll(/\s+/g," ").substring(0,30),"...")),console.debug(t),console.groupEnd(),[4,null===(o=this.sqliteConnection)||void 0===o?void 0:o.saveToStore("".concat(this.name,"."))]):[3,3];case 2:e.sent(),e.label=3;case 3:return[2,r]}}))}))},i}();exports.default=i;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("jeep-sqlite/loader"),n=require("@capacitor-community/sqlite");function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=i(require("@flumens/utils/dist/deferred")),s=function(){function i(e){var t=e.name,i=e.debug,s=e.web;this.sqliteConnection=new n.SQLiteConnection(n.CapacitorSQLite),this.name="main",this.debug=!1,this.isWeb=!1,this.ready=new r.default,this.name=t||this.name,this.debug=i||this.debug,this.isWeb=s||this.isWeb}return i.migrateCordova=function(){var t;return e.__awaiter(this,void 0,void 0,(function(){var i,r;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,(i=new n.SQLiteConnection(n.CapacitorSQLite)).getMigratableDbList()];case 1:return r=e.sent(),(null===(t=r.values)||void 0===t?void 0:t.length)?[4,i.addSQLiteSuffix()]:[2];case 2:return e.sent(),[4,i.deleteOldDatabases()];case 3:return e.sent(),[2]}}))}))},Object.defineProperty(i.prototype,"db",{get:function(){return this.connection},enumerable:!1,configurable:!0}),i.prototype.init=function(){return e.__awaiter(this,void 0,void 0,(function(){var n,i;return e.__generator(this,(function(e){switch(e.label){case 0:return this.isWeb?(t.defineCustomElements(window),(n=document.createElement("jeep-sqlite")).setAttribute("autoSave","true"),document.body.appendChild(n),[4,customElements.whenDefined("jeep-sqlite")]):[3,3];case 1:return e.sent(),[4,this.sqliteConnection.initWebStore()];case 2:e.sent(),e.label=3;case 3:return i=this,[4,this.sqliteConnection.createConnection("".concat(this.name,"."),!1,"no-encryption",1,!1)];case 4:return i.connection=e.sent(),[4,this.connection.open()];case 5:return e.sent(),this.ready.resolve(!0),[2]}}))}))},i.prototype.query=function(t,n){var i;return e.__awaiter(this,void 0,void 0,(function(){var r;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:return e.sent(),[4,this.db.query(t,n).then((function(e){return e.values||[]}))];case 2:return r=e.sent(),this.debug?(console.groupCollapsed("💾 SQL: ".concat(t.trimStart().replaceAll(/\n/g," ").replaceAll(/\s+/g," ").substring(0,30),"...")),console.debug(t,n),console.groupEnd(),[4,null===(i=this.sqliteConnection)||void 0===i?void 0:i.saveToStore("".concat(this.name,"."))]):[3,4];case 3:e.sent(),e.label=4;case 4:return[2,r]}}))}))},i.prototype.getUrl=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.label){case 0:return this.isWeb?[2,""]:[4,this.db.getUrl()];case 1:return[2,e.sent().url]}}))}))},i}();exports.default=s;
@@ -1,16 +1,22 @@
1
+ import Deferred from '@flumens/utils/dist/deferred';
2
+ import SQLiteDatabase from './SQLiteDatabase';
1
3
  import Store, { ModelDTO } from './Store';
4
+ type SQLiteStoreOptions = {
5
+ db: SQLiteDatabase;
6
+ name: string;
7
+ debug?: boolean;
8
+ };
2
9
  export default class SQLiteStore implements Store {
3
- debugging: any;
4
- ready: any;
5
- dbName?: string;
6
- storeName?: string;
10
+ private debug;
11
+ ready: Deferred<boolean>;
12
+ private name;
7
13
  localForage: any;
8
- db: any;
9
- constructor({ debugging, name, storeName }: any);
14
+ db: SQLiteDatabase;
15
+ constructor({ db, name, debug }: SQLiteStoreOptions);
10
16
  init(): Promise<void>;
11
- save(val: ModelDTO): Promise<any>;
12
- find(cid: string | number): Promise<ModelDTO>;
13
- findAll(): Promise<any>;
17
+ save(val: ModelDTO): Promise<void>;
18
+ find(cid: string | number): Promise<ModelDTO | undefined>;
19
+ findAll(): Promise<ModelDTO[]>;
14
20
  destroy(cid: any): Promise<void>;
15
21
  destroyAll(): Promise<void>;
16
22
  /**
@@ -21,5 +27,5 @@ export default class SQLiteStore implements Store {
21
27
  * Imports objects to store.
22
28
  */
23
29
  import(obj: any): Promise<void>;
24
- _printDiff(cid: any, val: any): Promise<void>;
25
30
  }
31
+ export {};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("deep-diff"),r=require("jeep-sqlite/loader"),n=require("lodash"),i=require("@ionic/react"),a=require("./SQLiteDatabase.js");if(!i.isPlatform("hybrid")){r.defineCustomElements(window);var s=document.createElement("jeep-sqlite");s.setAttribute("autoSave","true"),document.body.appendChild(s)}var o=function(t){var e=t.id,r=t.cid,n=t.data;return{id:e,cid:r,createdAt:t.created_at,updatedAt:t.updated_at,syncedAt:t.synced_at,attrs:n}},d=function(){function r(t){var e=t.debugging,r=t.name,n=t.storeName;this.debugging=e,this.dbName=r,this.storeName=n,this.db=new a.default(r,e),this.ready=this.init(),window.db=this.db}return r.prototype.init=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(t){switch(t.label){case 0:return i.isPlatform("hybrid")?[3,2]:[4,customElements.whenDefined("jeep-sqlite")];case 1:t.sent(),t.label=2;case 2:if(!this.storeName)throw new Error("storeName prop is missing");return[4,this.db.init()];case 3:return t.sent(),e="\n CREATE TABLE IF NOT EXISTS ".concat(this.storeName,"\n (\n id VARCHAR(36),\n cid VARCHAR(36) PRIMARY KEY NOT NULL DEFAULT id,\n data JSONB NOT NULL,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n synced_at INTEGER\n );\n "),[4,this.db.query(e)];case 4:return t.sent(),[2]}}))}))},r.prototype.save=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n,i,a,s,o,d;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:if(t.sent(),!e.cid)throw new Error("Invalid cid passed to store");return r=e.cid,n=e.id,i=e.createdAt,a=e.updatedAt,s=e.syncedAt,o=e.attrs,this.debugging?[4,this._printDiff(r,e)]:[3,3];case 2:t.sent(),t.label=3;case 3:return d="\n INSERT INTO ".concat(this.storeName,"(id, cid, data, created_at, updated_at, synced_at)\n VALUES (?, ?, jsonb(?), ?, ?, ?)\n ON CONFLICT(cid) DO UPDATE SET data = excluded.data;\n "),[2,this.db.query(d,[n,r,JSON.stringify(o),new Date(i).getTime(),new Date(a).getTime(),s?new Date(s).getTime():null])]}}))}))},r.prototype.find=function(e){var r,n;return t.__awaiter(this,void 0,void 0,(function(){var i,a,s;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:if(t.sent(),!e)throw new Error("Invalid cid passed to store");return i="\n SELECT id, cid, json(data) as data, created_at, updated_at, synced_at,\n FROM ".concat(this.storeName,"\n WHERE cid = ?;\n "),[4,this.db.query(i,[e])];case 2:return a=t.sent(),s=(null===(n=null===(r=a.values)||void 0===r?void 0:r[0])||void 0===n?void 0:n["json(data)"])||null,[2,o(JSON.parse(s))]}}))}))},r.prototype.findAll=function(){var e;return t.__awaiter(this,void 0,void 0,(function(){var r,n;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),r="\n SELECT id, cid, json(data) as data, created_at, updated_at, synced_at,\n FROM ".concat(this.storeName,";\n "),[4,this.db.query(r)];case 2:return n=t.sent(),[2,(null===(e=n.values)||void 0===e?void 0:e.map((function(t){return o(JSON.parse(null==t?void 0:t["json(data)"])||null)})))||[]]}}))}))},r.prototype.destroy=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:if(t.sent(),!e)throw new Error("Invalid cid passed to store");return r="DELETE from ".concat(this.storeName,' where cid = "').concat(e,'"'),[4,this.db.query(r)];case 2:return t.sent(),[2]}}))}))},r.prototype.destroyAll=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),e="DELETE from ".concat(this.storeName),[4,this.db.query(e)];case 2:return t.sent(),[2]}}))}))},r.prototype.export=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(r){switch(r.label){case 0:return[4,this.ready];case 1:return r.sent(),e=function(e,r){var n;return t.__assign(t.__assign({},e),((n={})[r.cid]=r,n))},[4,this.findAll()];case 2:return[2,r.sent().reduce(e,{})]}}))}))},r.prototype.import=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),[4,this.destroyAll()];case 2:if(t.sent(),"object"!=typeof e)throw new Error("Invalid obj passed to store");return r=Object.entries(e).map((function(t){var e=t[1];return n.save(e)})),Promise.all(r),[2]}}))}))},r.prototype._printDiff=function(r,i){return t.__awaiter(this,void 0,void 0,(function(){var a,s,o,d,c,u,l;return t.__generator(this,(function(t){switch(t.label){case 0:return a=this.storeName||"",[4,this.find(r)];case 1:return s=t.sent(),(o=e.diff(s,i))?(d={},c=0,u="",o.forEach((function(t){var e,i,s=((e={})[a]=((i={})[r]={},i),e);if(!t.path)return s[a][r]=t.rhs,console.groupCollapsed("Δ + ".concat(r)),console.log(s),void console.groupEnd();t.path.reduce((function(e,r,n){if(t.path.length-1>n)return e[r]={},e[r];var i=JSON.stringify(t.lhs,null,2),a=JSON.stringify(t.rhs,null,2);if(i===a)return e[r];c++,e[r]="".concat(i," -> ").concat(a),u="".concat(r,": ").concat(i," -> ").concat(a)}),s[a][r]),d=n.merge(d,s)})),c&&(l="Δ ".concat(r),1===c&&(l+=" ".concat(u)),console.groupCollapsed(l),console.log(d),console.groupEnd()),[2]):[2]}}))}))},r}();exports.default=d;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("@flumens/utils/dist/deferred"),n=require("./utils.js");function r(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var a=r(e),d=function(t){var e=t.id,n=t.cid,r=t.data;return{id:e,cid:n,createdAt:t.created_at,updatedAt:t.updated_at,syncedAt:t.synced_at,attrs:JSON.parse(r)}},i=function(){function e(t){var e=t.db,n=t.name,r=t.debug;this.debug=!1,this.ready=new a.default,this.db=e,this.name=n,this.debug=r||this.debug,this.init()}return e.prototype.init=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.db.ready];case 1:return t.sent(),e="\n CREATE TABLE IF NOT EXISTS ".concat(this.name,"\n (\n id VARCHAR(36),\n cid VARCHAR(36) PRIMARY KEY NOT NULL DEFAULT id,\n data JSONB NOT NULL,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n synced_at INTEGER\n );\n "),[4,this.db.query(e)];case 2:return t.sent(),this.ready.resolve(!0),[2]}}))}))},e.prototype.save=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,a,d,i,s,c,u,o;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:if(t.sent(),!e.cid)throw new Error("Invalid cid passed to store");return r=e.cid,a=e.id,d=e.createdAt,i=e.updatedAt,s=e.syncedAt,c=e.attrs,this.debug?[4,this.find(r)]:[3,3];case 2:u=t.sent(),n.printDiff(u,e,r,this.name),t.label=3;case 3:return o="\n INSERT INTO ".concat(this.name,"(id, cid, data, created_at, updated_at, synced_at)\n VALUES (?, ?, jsonb(?), ?, ?, ?)\n ON CONFLICT(cid) DO UPDATE SET \n id = excluded.id, \n cid = excluded.cid, \n data = excluded.data, \n created_at = \n excluded.created_at, \n updated_at = \n excluded.updated_at, \n synced_at = \n excluded.synced_at;\n "),[4,this.db.query(o,[a||null,r,JSON.stringify(c),new Date(d).getTime(),new Date(i).getTime(),s?new Date(s).getTime():null])];case 4:return t.sent(),[2]}}))}))},e.prototype.find=function(e){return t.__awaiter(this,void 0,void 0,(function(){var n,r;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:if(t.sent(),!e)throw new Error("Invalid cid passed to store");return n="\n SELECT id, cid, json(data) as data, created_at, updated_at, synced_at\n FROM ".concat(this.name,"\n WHERE cid = ?;\n "),[4,this.db.query(n,[e])];case 2:return[2,(r=t.sent()[0])?d(r):void 0]}}))}))},e.prototype.findAll=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),e="\n SELECT id, cid, json(data) as data, created_at, updated_at, synced_at\n FROM ".concat(this.name,";\n "),[4,this.db.query(e)];case 2:return[2,t.sent().map(d)]}}))}))},e.prototype.destroy=function(e){return t.__awaiter(this,void 0,void 0,(function(){var n;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:if(t.sent(),!e)throw new Error("Invalid cid passed to store");return n="DELETE from ".concat(this.name,' where cid = "').concat(e,'"'),[4,this.db.query(n)];case 2:return t.sent(),[2]}}))}))},e.prototype.destroyAll=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),e="DELETE from ".concat(this.name),[4,this.db.query(e)];case 2:return t.sent(),[2]}}))}))},e.prototype.export=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(n){switch(n.label){case 0:return[4,this.ready];case 1:return n.sent(),e=function(e,n){var r;return t.__assign(t.__assign({},e),((r={})[n.cid]=n,r))},[4,this.findAll()];case 2:return[2,n.sent().reduce(e,{})]}}))}))},e.prototype.import=function(e){return t.__awaiter(this,void 0,void 0,(function(){var n,r,a=this;return t.__generator(this,(function(d){switch(d.label){case 0:return[4,this.ready];case 1:return d.sent(),[4,this.destroyAll()];case 2:if(d.sent(),"object"!=typeof e)throw new Error("Invalid obj passed to store");return n=function(e){var n,r,a,d,i,s;if(!e.createdAt&&(null===(n=e.metadata)||void 0===n?void 0:n.createdOn)&&(e.createdAt=null===(r=e.metadata)||void 0===r?void 0:r.createdOn),!e.updatedAt&&(null===(a=e.metadata)||void 0===a?void 0:a.updatedOn)&&(e.updatedAt=null===(d=e.metadata)||void 0===d?void 0:d.updatedOn),!e.syncedAt&&(null===(i=e.metadata)||void 0===i?void 0:i.syncedOn)&&(e.syncedAt=null===(s=e.metadata)||void 0===s?void 0:s.syncedOn),e.samples){var c=e.id,u=e.cid,o=e.createdAt,l=e.updatedAt,h=e.syncedAt,_=t.__rest(e,["id","cid","createdAt","updatedAt","syncedAt"]);e={id:c,cid:u,createdAt:o,updatedAt:l,syncedAt:h,attrs:t.__assign({},_)}}return e},r=Object.entries(e).map((function(t){var e=t[1];return a.save(n(e))})),Promise.all(r),[2]}}))}))},e}();exports.default=i;
@@ -8,7 +8,7 @@ export type ModelDTO = {
8
8
  };
9
9
  export default interface Store {
10
10
  save(val: ModelDTO): Promise<void>;
11
- find(cid: any): Promise<ModelDTO>;
11
+ find(cid: any): Promise<ModelDTO | undefined>;
12
12
  findAll(): Promise<ModelDTO[]>;
13
13
  destroy(cid: any): Promise<void>;
14
14
  destroyAll(): Promise<void>;
@@ -1,3 +1,4 @@
1
+ export { default as SQLiteDatabase } from './SQLiteDatabase';
1
2
  export { default as LocalForageStore } from './LocalForageStore';
2
3
  export { default as SQLiteStore } from './SQLiteStore';
3
4
  export { default as IStore } from './Store';
@@ -0,0 +1 @@
1
+ export declare function printDiff(currentVal: any, val: any, cid: string, name?: string): void;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var o=require("deep-diff"),r=require("lodash");exports.printDiff=function(e,n,c,t){void 0===t&&(t="");var a=o.diff(e,n);if(a){var i={},l=0,s="";if(a.forEach((function(o){var e,n,a=((e={})[t]=((n={})[c]={},n),e);if(!o.path)return a[t][c]=o.rhs,console.groupCollapsed("Δ + ".concat(c)),console.log(a),void console.groupEnd();o.path.reduce((function(r,e,n){if(o.path.length-1>n)return r[e]={},r[e];var c=JSON.stringify(o.lhs,null,2),t=JSON.stringify(o.rhs,null,2);if(c===t)return r[e];l++,r[e]="".concat(c," -> ").concat(t),s="".concat(e,": ").concat(c," -> ").concat(t)}),a[t][c]),i=r.merge(i,a)})),l){var f="Δ ".concat(c);1===l&&(f+=" ".concat(s)),console.groupCollapsed(f),console.log(i),console.groupEnd()}}};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./DrupalUserModel.js"),r=require("./initStoredSamples.js"),t=require("./Stores/LocalForageStore.js"),i=require("./Stores/SQLiteStore.js"),o=require("./Model.js"),a=require("./Collection/index.js"),s=require("./Indicia/Media.js"),l=require("./Indicia/Occurrence.js"),d=require("./Indicia/Sample.js");exports.DrupalUserModel=e.default,exports.initStoredSamples=r.default,exports.LocalForageStore=t.default,exports.SQLiteStore=i.default,exports.Model=o.default,exports.Collection=a.default,exports.IndiciaMedia=s.default,exports.IndiciaOccurrence=l.default,exports.IndiciaSample=d.default;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./DrupalUserModel.js"),r=require("./initStoredSamples.js"),t=require("./Stores/SQLiteDatabase.js"),i=require("./Stores/LocalForageStore.js"),a=require("./Stores/SQLiteStore.js"),o=require("./Model.js"),s=require("./Collection/index.js"),l=require("./Indicia/Media.js"),d=require("./Indicia/Occurrence.js"),u=require("./Indicia/Sample.js");exports.DrupalUserModel=e.default,exports.initStoredSamples=r.default,exports.SQLiteDatabase=t.default,exports.LocalForageStore=i.default,exports.SQLiteStore=a.default,exports.Model=o.default,exports.Collection=s.default,exports.IndiciaMedia=l.default,exports.IndiciaOccurrence=d.default,exports.IndiciaSample=u.default;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("mobx");exports.default=function(r,t){var n=e.observable([]);e.observe(n,(function(e){e.addedCount&&(e.added[0].collection=n)}));var o=function(e){var r=t.fromJSON(e);n.push(r)};return n.ready=r.findAll().then((function(e){return e.forEach(o)})),n._init=n.ready,n.removeAllSynced=function(){var e=[];return n.forEach((function(r){r.syncedAt&&e.push(r.destroy())})),Promise.all(e)},n.comparator=function(e){return-new Date(e.createdAt).getTime()},n.resetDefaults=function(){var e=n.map((function(e){return e.destroy()}));return Promise.all(e)},n};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("mobx");exports.default=function(r,t){var n=e.observable([]);e.observe(n,(function(e){e.addedCount&&(e.added[0].collection=n)}));var o=function(e){var r=t.fromJSON(e);n.push(r)};return n.ready=r.findAll().then((function(e){return e.forEach(o)})),n.removeAllSynced=function(){var e=[];return n.forEach((function(r){r.syncedAt&&e.push(r.destroy())})),Promise.all(e)},n.comparator=function(e){return-new Date(e.createdAt).getTime()},n.resetDefaults=function(){var e=n.map((function(e){return e.destroy()}));return Promise.all(e)},n};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flumens/models",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/src/index.d.ts",
6
6
  "scripts": {
@@ -29,7 +29,9 @@
29
29
  "tslib": "2.6.2",
30
30
  "typescript": "4.9.4"
31
31
  },
32
- "peerDependencies": {},
32
+ "peerDependencies": {
33
+ "@flumens/utils": "*"
34
+ },
33
35
  "optionalDependencies": {
34
36
  "localforage": "^1",
35
37
  "jwt-decode": "^4",