@flumens/models 0.6.0 → 0.7.0
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.
- package/dist/Collection.js +1 -108
- package/dist/Drupal/User.d.ts +6 -6
- package/dist/Drupal/User.js +1 -433
- package/dist/Indicia/ElasticOccurrence.d.ts +5 -0
- package/dist/Indicia/ElasticOccurrence.js +1 -0
- package/dist/Indicia/ElasticSample.d.ts +11 -0
- package/dist/Indicia/ElasticSample.js +1 -0
- package/dist/Indicia/Media.d.ts +5 -7
- package/dist/Indicia/Media.js +1 -369
- package/dist/Indicia/Occurrence.d.ts +30 -8
- package/dist/Indicia/Occurrence.js +1 -220
- package/dist/Indicia/Sample.d.ts +54 -11
- package/dist/Indicia/Sample.js +1 -687
- package/dist/Indicia/SampleCollection.d.ts +12 -4
- package/dist/Indicia/SampleCollection.js +1 -77
- package/dist/Indicia/helpers.d.ts +9 -0
- package/dist/Indicia/helpers.js +1 -120
- package/dist/Model.d.ts +10 -9
- package/dist/Model.js +1 -191
- package/dist/Stores/LocalForageStore.js +1 -228
- package/dist/Stores/SQLiteDatabase.js +1 -221
- package/dist/Stores/SQLiteStore.js +1 -310
- package/dist/Stores/Store.js +1 -11
- package/dist/Stores/utils.js +1 -60
- package/dist/index.js +1 -29
- package/package.json +5 -2
|
@@ -1,14 +1,22 @@
|
|
|
1
1
|
import Collection, { Options as CollectionOptions } from '../Collection';
|
|
2
2
|
import Store from '../Stores/Store';
|
|
3
|
-
import
|
|
4
|
-
|
|
3
|
+
import Occurrence from './Occurrence';
|
|
4
|
+
import Sample, { Remote } from './Sample';
|
|
5
|
+
export type Options<T extends Sample> = {
|
|
5
6
|
models?: T[];
|
|
6
7
|
store?: Store;
|
|
7
|
-
Model?: typeof
|
|
8
|
+
Model?: typeof Sample<any, any>;
|
|
9
|
+
Occurrence?: typeof Occurrence<any, any>;
|
|
10
|
+
url?: Remote['url'];
|
|
11
|
+
getAccessToken?: Remote['getAccessToken'];
|
|
8
12
|
} & CollectionOptions<T>;
|
|
9
|
-
export default class SampleCollection<T extends
|
|
13
|
+
export default class SampleCollection<T extends Sample> extends Collection<T> {
|
|
14
|
+
remote: Remote;
|
|
15
|
+
Occurrence?: typeof Occurrence<any, any>;
|
|
16
|
+
cidMap: Map<string, Sample>;
|
|
10
17
|
constructor(options: Options<T>);
|
|
11
18
|
fetch: () => Promise<void>;
|
|
19
|
+
fetchRemote: (from: number, surveyIDs: any[]) => Promise<T[]>;
|
|
12
20
|
removeAllSynced: () => Promise<any[]>;
|
|
13
21
|
/**
|
|
14
22
|
* Reverse order so that newest are at the top of list.
|
|
@@ -1,77 +1 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
-
|
|
5
|
-
var tslib = require('tslib');
|
|
6
|
-
var mobx = require('mobx');
|
|
7
|
-
var Collection = require('../Collection.js');
|
|
8
|
-
|
|
9
|
-
var SampleCollection = /** @class */ (function (_super) {
|
|
10
|
-
tslib.__extends(SampleCollection, _super);
|
|
11
|
-
function SampleCollection(options) {
|
|
12
|
-
var _this = _super.call(this, options) || this;
|
|
13
|
-
_this.fetch = function () { return tslib.__awaiter(_this, void 0, void 0, function () {
|
|
14
|
-
var modelsJSON, getModel, models;
|
|
15
|
-
var _this = this;
|
|
16
|
-
return tslib.__generator(this, function (_a) {
|
|
17
|
-
switch (_a.label) {
|
|
18
|
-
case 0:
|
|
19
|
-
if (!this.store || !this.Model) {
|
|
20
|
-
this.ready.resolve(false);
|
|
21
|
-
return [2 /*return*/];
|
|
22
|
-
}
|
|
23
|
-
return [4 /*yield*/, this.store.findAll()];
|
|
24
|
-
case 1:
|
|
25
|
-
modelsJSON = _a.sent();
|
|
26
|
-
getModel = function (json) {
|
|
27
|
-
return _this.Model.fromJSON(tslib.__assign(tslib.__assign({}, json), { attrs: json.data }));
|
|
28
|
-
};
|
|
29
|
-
models = modelsJSON.map(getModel);
|
|
30
|
-
this.push.apply(this, models);
|
|
31
|
-
this.ready.resolve(true);
|
|
32
|
-
return [2 /*return*/];
|
|
33
|
-
}
|
|
34
|
-
});
|
|
35
|
-
}); };
|
|
36
|
-
_this.removeAllSynced = function () {
|
|
37
|
-
var toWait = [];
|
|
38
|
-
_this.forEach(function (sample) {
|
|
39
|
-
if (sample.syncedAt) {
|
|
40
|
-
toWait.push(sample.destroy());
|
|
41
|
-
}
|
|
42
|
-
});
|
|
43
|
-
return Promise.all(toWait);
|
|
44
|
-
};
|
|
45
|
-
/**
|
|
46
|
-
* Reverse order so that newest are at the top of list.
|
|
47
|
-
*/
|
|
48
|
-
_this.comparator = function (a) {
|
|
49
|
-
var date = new Date(a.createdAt);
|
|
50
|
-
return -date.getTime();
|
|
51
|
-
};
|
|
52
|
-
_this.reset = function () { return tslib.__awaiter(_this, void 0, void 0, function () {
|
|
53
|
-
var destroyAllSamples;
|
|
54
|
-
return tslib.__generator(this, function (_a) {
|
|
55
|
-
switch (_a.label) {
|
|
56
|
-
case 0:
|
|
57
|
-
destroyAllSamples = this.map(function (sample) { return sample.destroy(); });
|
|
58
|
-
return [4 /*yield*/, Promise.all(destroyAllSamples)];
|
|
59
|
-
case 1:
|
|
60
|
-
_a.sent();
|
|
61
|
-
return [2 /*return*/];
|
|
62
|
-
}
|
|
63
|
-
});
|
|
64
|
-
}); };
|
|
65
|
-
var attachCollectionToModels = function (change) {
|
|
66
|
-
if (change.addedCount)
|
|
67
|
-
change.added.forEach(function (model) { return (model.collection = _this); }); // eslint-disable-line no-return-assign, no-param-reassign
|
|
68
|
-
if (change.removedCount)
|
|
69
|
-
change.removed.forEach(function (model) { return delete model.collection; }); // eslint-disable-line no-param-reassign
|
|
70
|
-
};
|
|
71
|
-
mobx.observe(_this, attachCollectionToModels);
|
|
72
|
-
return _this;
|
|
73
|
-
}
|
|
74
|
-
return SampleCollection;
|
|
75
|
-
}(Collection["default"]));
|
|
76
|
-
|
|
77
|
-
exports["default"] = SampleCollection;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("axios"),n=require("../Collection.js"),a=require("./ElasticOccurrence.js"),s=require("./ElasticSample.js");function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var c=i(r),o=function(r){function n(n){var i=r.call(this,n)||this;i.remote=t.observable({synchronising:!1,url:null,getAccessToken:function(){return Promise.resolve("auth token is missing")},timeout:12e4}),i.fetch=function(){return e.__awaiter(i,void 0,void 0,(function(){var t,r,n,a=this;return e.__generator(this,(function(s){switch(s.label){case 0:return this.store&&this.Model?[4,this.store.findAll()]:(this.ready.resolve(!1),[2]);case 1:return t=s.sent(),r=function(t){var r=t.data,n=r.data,s=r.metadata,i=r.occurrences,c=r.samples,o=r.media;return new a.Model(e.__assign(e.__assign({},t),{data:n,metadata:s,occurrences:i,samples:c,media:o}))},n=t.map(r),this.push.apply(this,n),this.ready.resolve(!0),[2]}}))}))},i.fetchRemote=function(t,r){return e.__awaiter(i,void 0,void 0,(function(){var n,i,o,u,d,l,f,m,h,p,v,_,y,g,b,w,A,O,S,M,k,E,T=this;return e.__generator(this,(function(j){switch(j.label){case 0:return console.log("Fetching remote samples, page",t),n={bool:{must_not:{exists:{field:"event.parent_event_id"}}}},i={match:{"metadata.trial":"false"}},o=function(e){return{match:{"metadata.survey.id":e}}},u={bool:{should:r.map(o)}},d=[u,n,i],l=JSON.stringify({from:t,size:100,query:{bool:{must:d}},sort:[{"metadata.created_on":"desc"}]}),f=this.remote.url,[4,this.remote.getAccessToken()];case 1:return m=j.sent(),h={method:"post",url:"".concat(f,"/index.php/services/rest/es-samples/_search"),headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(m)},data:l},[4,c.default.request(h)];case 2:return p=j.sent(),v=function(e){return e._source},_=p.data.hits.hits.map(v),y=_.map((function(e){return e.id})),g=s.fetchElasticSubSamples({parentId:y,url:f,accessToken:m}),b=a.fetchElasticOccurrences({parentId:y,url:f,accessToken:m}),[4,Promise.all([g,b])];case 3:return w=j.sent(),A=w[0],O=w[1],S=function(e){return!!e},M=_.map(function(t,r,n,a,s){return function(i){var c,o,u=(new Date).getTime();try{var d=new n({skipStore:!0});d.data.surveyId=i.metadata.survey.id;var l=d.getSurvey(),f=n.parseRemoteJSON(i,t,l);d.id=f.id,d.cid=f.cid||d.cid,Object.assign(d.data,f.data),Object.assign(d.metadata,f.metadata);var m=function(e){return e.event.parent_event_id===d.id||e.event.event_id===d.id},h=a.filter(m).map((function(e){var r=n.parseRemoteJSON(e,t,l),a=new n(r);return a.syncedAt=u,a})),p=h.reduce((function(t,r){var n;return e.__assign(e.__assign({},t),((n={})[r.id]=r,n))}),((c={})[d.id]=d,c));return s.filter(m).map((function(e){var n=r.parseRemoteJSON(e,t,l),a=new r(n);return a.syncedAt=u,[a,e.event.event_id]})).forEach((function(e){var t=e[0],r=e[1];r!==parseInt(d.id,10)?p[r]?p[r].occurrences.push(t):console.error("Can't attach occ to missing ".concat(r," sample")):d.occurrences.push(t)})),(o=d.samples).push.apply(o,h),d.syncedAt=u,d}catch(e){return console.warn(JSON.stringify(i)),console.error(e),null}}}(f,this.Occurrence,this.Model,A,O)).filter(S),k=function(e){return!T.cidMap.has(e.cid)},E=M.filter(k),this.push.apply(this,E),[2,E]}}))}))},i.removeAllSynced=function(){var e=[];return i.forEach((function(t){t.syncedAt&&e.push(t.destroy())})),Promise.all(e)},i.comparator=function(e){return-new Date(e.createdAt).getTime()},i.reset=function(){return e.__awaiter(i,void 0,void 0,(function(){var t;return e.__generator(this,(function(e){switch(e.label){case 0:return t=this.map((function(e){return e.destroy()})),[4,Promise.all(t)];case 1:return e.sent(),[2]}}))}))},i.Occurrence=n.Occurrence,i.remote.url=n.url,i.remote.getAccessToken=n.getAccessToken,i.cidMap=new Map;t.intercept(i,(function(e){if(e.added&&e.added.length){e.added.forEach((function(e){i.cidMap.set(e.cid,e)}))}if(e.removedCount>0){var t=Array.from(i.cidMap.keys())[e.index];i.cidMap.delete(t)}return e}));return t.observe(i,(function(e){e.addedCount&&e.added.forEach((function(e){return e.collection=i})),e.removedCount&&e.removed.forEach((function(e){return delete e.collection}))})),i}return e.__extends(n,r),n}(n.default);exports.default=o;
|
|
@@ -29,3 +29,12 @@ export declare function validateRemoteModel(): {
|
|
|
29
29
|
model: any;
|
|
30
30
|
models: any;
|
|
31
31
|
} | null;
|
|
32
|
+
interface RemoteAttr {
|
|
33
|
+
value: any;
|
|
34
|
+
id: string;
|
|
35
|
+
}
|
|
36
|
+
type AttrConfig = any;
|
|
37
|
+
export declare const parseRemoteAttrs: (config: {
|
|
38
|
+
[key: string]: AttrConfig;
|
|
39
|
+
}, remoteAttrs: RemoteAttr[]) => any;
|
|
40
|
+
export {};
|
package/dist/Indicia/helpers.js
CHANGED
|
@@ -1,120 +1 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
-
|
|
5
|
-
var tslib = require('tslib');
|
|
6
|
-
|
|
7
|
-
var getErrorMessageFromObject = function (errors) {
|
|
8
|
-
return Object.entries(errors).reduce(function (string, err) { return "".concat(string).concat(err[0], " ").concat(err[1], "\n"); }, '');
|
|
9
|
-
};
|
|
10
|
-
/**
|
|
11
|
-
* Converts DataURI object to a Blob.
|
|
12
|
-
*
|
|
13
|
-
* @param {type} dataURI
|
|
14
|
-
* @param {type} fileType
|
|
15
|
-
* @returns {undefined}
|
|
16
|
-
*/
|
|
17
|
-
function dataURItoBlob(dataURI, fileType) {
|
|
18
|
-
var binary = atob(dataURI.split(',')[1]);
|
|
19
|
-
var array = [];
|
|
20
|
-
for (var i = 0; i < binary.length; i++) {
|
|
21
|
-
array.push(binary.charCodeAt(i));
|
|
22
|
-
}
|
|
23
|
-
return new Blob([new Uint8Array(array)], {
|
|
24
|
-
type: fileType,
|
|
25
|
-
});
|
|
26
|
-
}
|
|
27
|
-
// Detecting data URLs
|
|
28
|
-
// https://gist.github.com/bgrins/6194623
|
|
29
|
-
// data URI - MDN https://developer.mozilla.org/en-US/docs/data_URIs
|
|
30
|
-
// The 'data' URL scheme: http://tools.ietf.org/html/rfc2397
|
|
31
|
-
// Valid URL Characters: http://tools.ietf.org/html/rfc2396#section2
|
|
32
|
-
function isDataURL(string) {
|
|
33
|
-
if (!string) {
|
|
34
|
-
return false;
|
|
35
|
-
}
|
|
36
|
-
var normalized = string.toString(); // numbers
|
|
37
|
-
/* eslint-disable no-useless-escape, max-len */
|
|
38
|
-
var regex = /^\s*data:([a-z]+\/[a-z]+(;[a-z\-]+\=[a-z\-]+)?)?(;base64)?,[a-z0-9\!\$\&\'\,\(\)\*\+\,\;\=\-\.\_\~\:\@\/\?\%\s]*\s*$/i;
|
|
39
|
-
return !!normalized.match(regex);
|
|
40
|
-
}
|
|
41
|
-
function getBlobFromURL(url, mediaType) {
|
|
42
|
-
if (isDataURL(url)) {
|
|
43
|
-
var blob = dataURItoBlob(url, mediaType);
|
|
44
|
-
return Promise.resolve(blob);
|
|
45
|
-
}
|
|
46
|
-
return new Promise(function (resolve) {
|
|
47
|
-
// load image
|
|
48
|
-
var xhr = new XMLHttpRequest();
|
|
49
|
-
xhr.open('GET', url, true);
|
|
50
|
-
xhr.responseType = 'blob';
|
|
51
|
-
xhr.onload = function () {
|
|
52
|
-
var blob = xhr.response;
|
|
53
|
-
resolve(blob);
|
|
54
|
-
};
|
|
55
|
-
// todo check error case
|
|
56
|
-
xhr.send();
|
|
57
|
-
});
|
|
58
|
-
}
|
|
59
|
-
var boolToWarehouseValue = function (val) {
|
|
60
|
-
return val === true || val === 't' ? 't' : 'f';
|
|
61
|
-
};
|
|
62
|
-
function validateRemoteModel() {
|
|
63
|
-
// @ts-ignore
|
|
64
|
-
var survey = this.getSurvey();
|
|
65
|
-
// @ts-ignore
|
|
66
|
-
var error = survey.verify && survey.verify(this.attrs, this);
|
|
67
|
-
var attributes = {};
|
|
68
|
-
if (error) {
|
|
69
|
-
var isYupError = (error === null || error === void 0 ? void 0 : error.name) === 'ValidationError' ||
|
|
70
|
-
(error === null || error === void 0 ? void 0 : error.type) === 'ValidationError';
|
|
71
|
-
var isZodError = error && 'issues' in error;
|
|
72
|
-
var isPlainError = !isYupError && !isZodError;
|
|
73
|
-
if (isPlainError) {
|
|
74
|
-
attributes.errors = [error.message];
|
|
75
|
-
}
|
|
76
|
-
else if (isZodError) {
|
|
77
|
-
attributes.errors = error.issues.map(function (_a) {
|
|
78
|
-
var message = _a.message;
|
|
79
|
-
return message;
|
|
80
|
-
});
|
|
81
|
-
}
|
|
82
|
-
else {
|
|
83
|
-
attributes = tslib.__assign({}, error);
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
var validateSubModel = function (agg, model) {
|
|
87
|
-
var invalids = model.validateRemote();
|
|
88
|
-
if (invalids) {
|
|
89
|
-
agg[model.cid] = invalids; // eslint-disable-line
|
|
90
|
-
agg[model.cid].model = model; // eslint-disable-line
|
|
91
|
-
}
|
|
92
|
-
return agg;
|
|
93
|
-
};
|
|
94
|
-
// @ts-ignore
|
|
95
|
-
var samples = (this.samples || []).reduce(validateSubModel, {});
|
|
96
|
-
// @ts-ignore
|
|
97
|
-
var occurrences = (this.occurrences || []).reduce(validateSubModel, {});
|
|
98
|
-
// @ts-ignore
|
|
99
|
-
var media = (this.media || []).reduce(validateSubModel, {});
|
|
100
|
-
if (Object.keys(attributes).length ||
|
|
101
|
-
Object.keys(samples).length ||
|
|
102
|
-
Object.keys(occurrences).length ||
|
|
103
|
-
Object.keys(media).length) {
|
|
104
|
-
var models = tslib.__assign(tslib.__assign(tslib.__assign({}, samples), occurrences), media);
|
|
105
|
-
return {
|
|
106
|
-
attributes: attributes,
|
|
107
|
-
// @ts-ignore
|
|
108
|
-
model: this,
|
|
109
|
-
models: models,
|
|
110
|
-
};
|
|
111
|
-
}
|
|
112
|
-
return null;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
exports.boolToWarehouseValue = boolToWarehouseValue;
|
|
116
|
-
exports.dataURItoBlob = dataURItoBlob;
|
|
117
|
-
exports.getBlobFromURL = getBlobFromURL;
|
|
118
|
-
exports.getErrorMessageFromObject = getErrorMessageFromObject;
|
|
119
|
-
exports.isDataURL = isDataURL;
|
|
120
|
-
exports.validateRemoteModel = validateRemoteModel;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib");function t(e,t){for(var r=atob(e.split(",")[1]),n=[],s=0;s<r.length;s++)n.push(r.charCodeAt(s));return new Blob([new Uint8Array(n)],{type:t})}function r(e){if(!e)return!1;return!!e.toString().match(/^\s*data:([a-z]+\/[a-z]+(;[a-z\-]+\=[a-z\-]+)?)?(;base64)?,[a-z0-9\!\$\&\'\,\(\)\*\+\,\;\=\-\.\_\~\:\@\/\?\%\s]*\s*$/i)}exports.boolToWarehouseValue=function(e){return!0===e||"t"===e?"t":"f"},exports.dataURItoBlob=t,exports.getBlobFromURL=function(e,n){if(r(e)){var s=t(e,n);return Promise.resolve(s)}return new Promise((function(t){var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="blob",r.onload=function(){var e=r.response;t(e)},r.send()}))},exports.getErrorMessageFromObject=function(e){return Object.entries(e).reduce((function(e,t){return"".concat(e).concat(t[0]," ").concat(t[1],"\n")}),"")},exports.isDataURL=r,exports.parseRemoteAttrs=function(e,t){e=e||{};var r=Object.entries(e);return t.reduce((function(e,t){var n=r.find((function(e){var r;return(null===(r=e[1].remote)||void 0===r?void 0:r.id)===parseInt(t.id,10)}));if(!n)return e;var s=n[0],o=isNaN(t.value)?t.value:parseFloat(t.value);return e[s]=o,e}),{})},exports.validateRemoteModel=function(){var t=this.getSurvey(),r=t.verify&&t.verify(this.data,this),n={};if(r){var s=r&&"issues"in r;!("ValidationError"===(null==r?void 0:r.name)||"ValidationError"===(null==r?void 0:r.type))&&!s?n.errors=[r.message]:s?n.errors=r.issues.map((function(e){return e.message})):n=e.__assign({},r)}var o=function(e,t){var r=t.validateRemote();return r&&(e[t.cid]=r,e[t.cid].model=t),e},a=(this.samples||[]).reduce(o,{}),i=(this.occurrences||[]).reduce(o,{}),u=(this.media||[]).reduce(o,{});return Object.keys(n).length||Object.keys(a).length||Object.keys(i).length||Object.keys(u).length?{attributes:n,model:this,models:e.__assign(e.__assign(e.__assign({},a),i),u)}:null};
|
package/dist/Model.d.ts
CHANGED
|
@@ -1,21 +1,22 @@
|
|
|
1
1
|
import { Deferred } from '@flumens/utils';
|
|
2
2
|
import Store from './Stores/Store';
|
|
3
|
+
export declare const copyObject: (obj: any) => any;
|
|
3
4
|
export interface Options<T = any> {
|
|
4
5
|
id?: string;
|
|
5
6
|
cid?: string;
|
|
6
7
|
createdAt?: number;
|
|
7
8
|
updatedAt?: number;
|
|
8
9
|
syncedAt?: number;
|
|
9
|
-
|
|
10
|
+
data?: T;
|
|
10
11
|
store?: Store;
|
|
11
|
-
}
|
|
12
|
-
export interface Attrs {
|
|
13
12
|
/**
|
|
14
|
-
*
|
|
13
|
+
* @deprecated
|
|
15
14
|
*/
|
|
16
|
-
|
|
15
|
+
attrs?: any;
|
|
16
|
+
}
|
|
17
|
+
export interface Data {
|
|
17
18
|
}
|
|
18
|
-
export default class Model<T extends
|
|
19
|
+
export default class Model<T extends Data = Data> {
|
|
19
20
|
/**
|
|
20
21
|
* Remote server document ID.
|
|
21
22
|
*/
|
|
@@ -39,7 +40,7 @@ export default class Model<T extends Attrs = Attrs> {
|
|
|
39
40
|
/**
|
|
40
41
|
* Model's persistent observable attributes.
|
|
41
42
|
*/
|
|
42
|
-
|
|
43
|
+
data: T;
|
|
43
44
|
/**
|
|
44
45
|
* The offline store used to save and fetch the model from.
|
|
45
46
|
*/
|
|
@@ -56,7 +57,7 @@ export default class Model<T extends Attrs = Attrs> {
|
|
|
56
57
|
*/
|
|
57
58
|
readonly ready: Deferred<boolean>;
|
|
58
59
|
protected debouncedValue: number;
|
|
59
|
-
constructor({ id, cid, createdAt, updatedAt, syncedAt, attrs, store, }: Options);
|
|
60
|
+
constructor({ id, cid, createdAt, updatedAt, syncedAt, data, attrs, store, }: Options);
|
|
60
61
|
setUpdatedAtTimestamp(newUpdatedAt: number): void;
|
|
61
62
|
private _observerPaused;
|
|
62
63
|
/**
|
|
@@ -81,7 +82,7 @@ export default class Model<T extends Attrs = Attrs> {
|
|
|
81
82
|
createdAt: number;
|
|
82
83
|
updatedAt: number;
|
|
83
84
|
syncedAt: number | null | undefined;
|
|
84
|
-
|
|
85
|
+
data: T;
|
|
85
86
|
};
|
|
86
87
|
resetDefaults(defaultsToSet?: any): Promise<void>;
|
|
87
88
|
}
|
package/dist/Model.js
CHANGED
|
@@ -1,191 +1 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
-
|
|
5
|
-
var tslib = require('tslib');
|
|
6
|
-
var mobx = require('mobx');
|
|
7
|
-
var mobxUtils = require('mobx-utils');
|
|
8
|
-
var utils = require('@flumens/utils');
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* Simple object clone.
|
|
12
|
-
*/
|
|
13
|
-
var clone = function (obj) { return JSON.parse(JSON.stringify(obj)); };
|
|
14
|
-
var defaults = {
|
|
15
|
-
deleted: false,
|
|
16
|
-
};
|
|
17
|
-
var Model = /** @class */ (function () {
|
|
18
|
-
function Model(_a) {
|
|
19
|
-
var _b = _a.id, id = _b === void 0 ? '' : _b, _c = _a.cid, cid = _c === void 0 ? '' : _c, createdAt = _a.createdAt, updatedAt = _a.updatedAt, syncedAt = _a.syncedAt, _d = _a.attrs, attrs = _d === void 0 ? {} : _d, store = _a.store;
|
|
20
|
-
var _this = this;
|
|
21
|
-
/**
|
|
22
|
-
* A deferred promise to flag if the model was initialised from the store.
|
|
23
|
-
*/
|
|
24
|
-
this.ready = new utils.Deferred();
|
|
25
|
-
this.debouncedValue = 3000;
|
|
26
|
-
// a mechanism to disable auto-sync
|
|
27
|
-
this._observerPaused = false;
|
|
28
|
-
this.id = id;
|
|
29
|
-
this.cid = cid || id || utils.UUIDv7();
|
|
30
|
-
var now = Date.now();
|
|
31
|
-
this.createdAt = createdAt || now;
|
|
32
|
-
this.updatedAt = updatedAt || now;
|
|
33
|
-
this.syncedAt = syncedAt;
|
|
34
|
-
this.attrs = clone(tslib.__assign(tslib.__assign({}, defaults), attrs));
|
|
35
|
-
mobx.makeObservable(this, {
|
|
36
|
-
createdAt: mobx.observable,
|
|
37
|
-
updatedAt: mobx.observable,
|
|
38
|
-
syncedAt: mobx.observable,
|
|
39
|
-
attrs: mobx.observable,
|
|
40
|
-
});
|
|
41
|
-
this.store = store;
|
|
42
|
-
var isDebouncing;
|
|
43
|
-
var debouncedSync = function () {
|
|
44
|
-
var args = [];
|
|
45
|
-
for (var _i = 0; _i < arguments.length; _i++) {
|
|
46
|
-
args[_i] = arguments[_i];
|
|
47
|
-
}
|
|
48
|
-
clearTimeout(isDebouncing);
|
|
49
|
-
isDebouncing = setTimeout(function () { return _this.sync.apply(_this, args); }, // eslint-disable-line prefer-spread
|
|
50
|
-
_this.debouncedValue);
|
|
51
|
-
};
|
|
52
|
-
var setUpdatedTimestamp = function () {
|
|
53
|
-
if (_this._observerPaused)
|
|
54
|
-
return;
|
|
55
|
-
_this.updatedAt = Date.now();
|
|
56
|
-
debouncedSync();
|
|
57
|
-
};
|
|
58
|
-
mobxUtils.deepObserve(this.attrs, setUpdatedTimestamp);
|
|
59
|
-
}
|
|
60
|
-
Model.prototype.setUpdatedAtTimestamp = function (newUpdatedAt) {
|
|
61
|
-
this.updatedAt = newUpdatedAt;
|
|
62
|
-
};
|
|
63
|
-
/**
|
|
64
|
-
* Initialize the model from store.
|
|
65
|
-
*/
|
|
66
|
-
Model.prototype.fetch = function () {
|
|
67
|
-
return tslib.__awaiter(this, void 0, void 0, function () {
|
|
68
|
-
var document;
|
|
69
|
-
return tslib.__generator(this, function (_a) {
|
|
70
|
-
switch (_a.label) {
|
|
71
|
-
case 0:
|
|
72
|
-
if (!this.store) {
|
|
73
|
-
this.ready.resolve(false);
|
|
74
|
-
return [2 /*return*/];
|
|
75
|
-
}
|
|
76
|
-
return [4 /*yield*/, this.store.find(this.cid)];
|
|
77
|
-
case 1:
|
|
78
|
-
document = _a.sent();
|
|
79
|
-
if (!!document) return [3 /*break*/, 3];
|
|
80
|
-
return [4 /*yield*/, this.save()];
|
|
81
|
-
case 2:
|
|
82
|
-
_a.sent(); // persisting for the first time
|
|
83
|
-
this.ready.resolve(true);
|
|
84
|
-
return [2 /*return*/];
|
|
85
|
-
case 3:
|
|
86
|
-
if (document.id)
|
|
87
|
-
this.id = document.id; // checking presence for backwards compatibility
|
|
88
|
-
if (document.cid)
|
|
89
|
-
this.cid = document.cid; // checking presence for backwards compatibility
|
|
90
|
-
this._observerPaused = true;
|
|
91
|
-
mobx.set(this.attrs, document.data);
|
|
92
|
-
this._observerPaused = false;
|
|
93
|
-
this.createdAt = document.createdAt;
|
|
94
|
-
this.updatedAt = document.updatedAt;
|
|
95
|
-
this.syncedAt = document.syncedAt;
|
|
96
|
-
this.ready.resolve(true);
|
|
97
|
-
return [2 /*return*/];
|
|
98
|
-
}
|
|
99
|
-
});
|
|
100
|
-
});
|
|
101
|
-
};
|
|
102
|
-
/**
|
|
103
|
-
* Save the model to the offline store.
|
|
104
|
-
*/
|
|
105
|
-
Model.prototype.save = function () {
|
|
106
|
-
return tslib.__awaiter(this, void 0, void 0, function () {
|
|
107
|
-
var json;
|
|
108
|
-
return tslib.__generator(this, function (_a) {
|
|
109
|
-
switch (_a.label) {
|
|
110
|
-
case 0:
|
|
111
|
-
if (!this.store) {
|
|
112
|
-
throw new Error('Trying to save locally without a store');
|
|
113
|
-
}
|
|
114
|
-
json = this.toJSON();
|
|
115
|
-
return [4 /*yield*/, this.store.save(tslib.__assign(tslib.__assign({}, json), { data: json.attrs }))];
|
|
116
|
-
case 1:
|
|
117
|
-
_a.sent();
|
|
118
|
-
return [2 /*return*/];
|
|
119
|
-
}
|
|
120
|
-
});
|
|
121
|
-
});
|
|
122
|
-
};
|
|
123
|
-
/**
|
|
124
|
-
* Destroy the model and remove from the offline store.
|
|
125
|
-
*/
|
|
126
|
-
Model.prototype.destroy = function () {
|
|
127
|
-
return tslib.__awaiter(this, void 0, void 0, function () {
|
|
128
|
-
return tslib.__generator(this, function (_a) {
|
|
129
|
-
switch (_a.label) {
|
|
130
|
-
case 0:
|
|
131
|
-
if (!this.store) {
|
|
132
|
-
throw new Error('Trying to delete locally without a store');
|
|
133
|
-
}
|
|
134
|
-
return [4 /*yield*/, this.store.delete(this.cid)];
|
|
135
|
-
case 1:
|
|
136
|
-
_a.sent();
|
|
137
|
-
return [2 /*return*/];
|
|
138
|
-
}
|
|
139
|
-
});
|
|
140
|
-
});
|
|
141
|
-
};
|
|
142
|
-
// eslint-disable-next-line unused-imports/no-unused-vars
|
|
143
|
-
Model.prototype.sync = function () {
|
|
144
|
-
return tslib.__awaiter(this, void 0, void 0, function () {
|
|
145
|
-
return tslib.__generator(this, function (_a) {
|
|
146
|
-
switch (_a.label) {
|
|
147
|
-
case 0:
|
|
148
|
-
if (!this.store) return [3 /*break*/, 2];
|
|
149
|
-
return [4 /*yield*/, this.save()];
|
|
150
|
-
case 1:
|
|
151
|
-
_a.sent(); // if extended then store might be initialised in a subclass later
|
|
152
|
-
_a.label = 2;
|
|
153
|
-
case 2: return [2 /*return*/];
|
|
154
|
-
}
|
|
155
|
-
});
|
|
156
|
-
});
|
|
157
|
-
};
|
|
158
|
-
/**
|
|
159
|
-
* Returns a clean (no observables) JSON representation of the model.
|
|
160
|
-
*/
|
|
161
|
-
Model.prototype.toJSON = function () {
|
|
162
|
-
return {
|
|
163
|
-
id: this.id,
|
|
164
|
-
cid: this.cid,
|
|
165
|
-
createdAt: this.createdAt,
|
|
166
|
-
updatedAt: this.updatedAt,
|
|
167
|
-
syncedAt: this.syncedAt,
|
|
168
|
-
attrs: mobx.toJS(this.attrs),
|
|
169
|
-
};
|
|
170
|
-
};
|
|
171
|
-
Model.prototype.resetDefaults = function (defaultsToSet) {
|
|
172
|
-
var _this = this;
|
|
173
|
-
this.id = ''; // must be first in case a reaction is triggered from changing attrs that check this
|
|
174
|
-
var defaultsCopy = JSON.parse(JSON.stringify(tslib.__assign(tslib.__assign({}, defaults), defaultsToSet)));
|
|
175
|
-
mobx.set(this.attrs, defaultsCopy);
|
|
176
|
-
// clean up non-defaults
|
|
177
|
-
var defaultKeys = Object.keys(defaultsCopy);
|
|
178
|
-
var deleteProp = function (key) {
|
|
179
|
-
var isDefaultKey = defaultKeys.includes(key);
|
|
180
|
-
if (isDefaultKey)
|
|
181
|
-
return;
|
|
182
|
-
_this.attrs[key] = null; // might be a different type to current set value
|
|
183
|
-
delete _this.attrs[key];
|
|
184
|
-
};
|
|
185
|
-
Object.keys(this.attrs).forEach(deleteProp);
|
|
186
|
-
return this.save();
|
|
187
|
-
};
|
|
188
|
-
return Model;
|
|
189
|
-
}());
|
|
190
|
-
|
|
191
|
-
exports["default"] = Model;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),s=require("mobx-utils"),r=require("@flumens/utils"),i=function(t){return JSON.parse(JSON.stringify(t))},a={},n=function(){function n(n){var o=n.id,d=void 0===o?"":o,u=n.cid,c=void 0===u?"":u,h=n.createdAt,l=n.updatedAt,v=n.syncedAt,f=n.data,p=void 0===f?{}:f,y=n.attrs,_=void 0===y?{}:y,b=n.store,A=this;this.ready=new r.Deferred,this.debouncedValue=3e3,this._observerPaused=!1,this.id=d,this.cid=c||d||r.UUIDv7();var w,g=Date.now();this.createdAt=h||g,this.updatedAt=l||g,this.syncedAt=v,this.data=i(t.__assign(t.__assign(t.__assign({},a),p),_)),e.makeObservable(this,{createdAt:e.observable,updatedAt:e.observable,syncedAt:e.observable,data:e.observable}),this.store=b;s.deepObserve(this.data,(function(){A._observerPaused||(A.updatedAt=Date.now(),function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];clearTimeout(w),w=setTimeout((function(){return A.sync.apply(A,t)}),A.debouncedValue)}())}))}return n.prototype.setUpdatedAtTimestamp=function(t){this.updatedAt=t},n.prototype.fetch=function(){return t.__awaiter(this,void 0,void 0,(function(){var s;return t.__generator(this,(function(t){switch(t.label){case 0:return this.store?[4,this.store.find(this.cid)]:(this.ready.resolve(!1),[2]);case 1:return(s=t.sent())?[3,3]:[4,this.save()];case 2:return t.sent(),this.ready.resolve(!0),[2];case 3:return s.id&&(this.id=s.id),s.cid&&(this.cid=s.cid),this._observerPaused=!0,e.set(this.data,s.data),this._observerPaused=!1,this.createdAt=s.createdAt,this.updatedAt=s.updatedAt,this.syncedAt=s.syncedAt,this.ready.resolve(!0),[2]}}))}))},n.prototype.save=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;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 e=this.toJSON(),[4,this.store.save(e)];case 1:return t.sent(),[2]}}))}))},n.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.delete(this.cid)];case 1:return t.sent(),[2]}}))}))},n.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]}}))}))},n.prototype.toJSON=function(){return{id:this.id,cid:this.cid,createdAt:this.createdAt,updatedAt:this.updatedAt,syncedAt:this.syncedAt,data:e.toJS(this.data)}},n.prototype.resetDefaults=function(s){var r=this;this.id="";var i=JSON.parse(JSON.stringify(t.__assign(t.__assign({},a),s)));e.set(this.data,i);var n=Object.keys(i);return Object.keys(this.data).forEach((function(t){n.includes(t)||(r.data[t]=null,delete r.data[t])})),this.save()},n}();exports.copyObject=i,exports.default=n;
|