@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.
@@ -1,220 +1 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var tslib = require('tslib');
6
- var mobx = require('mobx');
7
- var lodash = require('lodash');
8
- var Model = require('../Model.js');
9
- var Media = require('./Media.js');
10
- var helpers = require('./helpers.js');
11
-
12
- var Occurrence = /** @class */ (function (_super) {
13
- tslib.__extends(Occurrence, _super);
14
- function Occurrence(_a) {
15
- if (_a === void 0) { _a = {}; }
16
- var _this = this;
17
- var _b = _a.metadata, metadata = _b === void 0 ? {} : _b, _c = _a.media, media = _c === void 0 ? [] : _c, options = tslib.__rest(_a, ["metadata", "media"]);
18
- _this = _super.call(this, options) || this;
19
- _this.debouncedValue = 300;
20
- _this.keys = function () {
21
- var getRemoteProps = function (attrs) {
22
- var extractRemoteIfExists = function (agg, key) {
23
- var _a;
24
- return (tslib.__assign(tslib.__assign({}, agg), (_a = {}, _a[key] = attrs[key].remote || attrs[key], _a)));
25
- };
26
- return Object.keys(attrs).reduce(extractRemoteIfExists, {});
27
- };
28
- return tslib.__assign(tslib.__assign({}, Occurrence.keys), getRemoteProps(_this.getSurvey().attrs || {}));
29
- };
30
- _this.metadata = mobx.observable(metadata);
31
- _this.media = mobx.observable(media);
32
- // eslint-disable-next-line no-param-reassign, no-return-assign
33
- var attachParent = function (model) { return (model.parent = _this); };
34
- _this.media.forEach(attachParent);
35
- var onAddedSetParentAndUpdateTime = function (change) {
36
- var _a;
37
- if ((_a = change.added) === null || _a === void 0 ? void 0 : _a.length) {
38
- change.added.forEach(attachParent);
39
- _this.setUpdatedAtTimestamp(Date.now());
40
- }
41
- else if (change.removedCount) {
42
- _this.setUpdatedAtTimestamp(Date.now());
43
- }
44
- return change;
45
- };
46
- mobx.intercept(_this.media, onAddedSetParentAndUpdateTime);
47
- return _this;
48
- }
49
- Occurrence.fromJSON = function (json, MediaClass) {
50
- var _a, _b, _c, _d;
51
- if (MediaClass === void 0) { MediaClass = Media["default"]; }
52
- var occurrence = new this(tslib.__assign(tslib.__assign({}, json), { createdAt: json.createdAt || ((_a = json.metadata) === null || _a === void 0 ? void 0 : _a.createdOn), updatedAt: json.updatedAt || ((_b = json.metadata) === null || _b === void 0 ? void 0 : _b.updatedOn), syncedAt: json.syncedAt || ((_c = json.metadata) === null || _c === void 0 ? void 0 : _c.syncedOn), media: (_d = json.media) === null || _d === void 0 ? void 0 : _d.map(function (mJson) { return MediaClass.fromJSON(mJson); }) }));
53
- return occurrence;
54
- };
55
- Occurrence.prototype.setUpdatedAtTimestamp = function (newUpdatedAt) {
56
- var _a;
57
- _super.prototype.setUpdatedAtTimestamp.call(this, newUpdatedAt);
58
- (_a = this.parent) === null || _a === void 0 ? void 0 : _a.setUpdatedAtTimestamp(newUpdatedAt);
59
- };
60
- /**
61
- * Save the model to the offline store.
62
- */
63
- Occurrence.prototype.save = function () {
64
- return tslib.__awaiter(this, void 0, void 0, function () {
65
- return tslib.__generator(this, function (_a) {
66
- if (!this.parent) {
67
- throw new Error('Trying to save locally without a parent');
68
- }
69
- this.parent.save();
70
- return [2 /*return*/];
71
- });
72
- });
73
- };
74
- /**
75
- * Destroy the model and remove from the offline store.
76
- */
77
- Occurrence.prototype.destroy = function (silent) {
78
- return tslib.__awaiter(this, void 0, void 0, function () {
79
- return tslib.__generator(this, function (_a) {
80
- switch (_a.label) {
81
- case 0:
82
- if (!this.parent) {
83
- throw new Error('Trying to destroy locally without a parent');
84
- }
85
- this.parent.occurrences.remove(this);
86
- return [4 /*yield*/, Promise.all(this.media.map(function (media) { return media.destroy(true); }))];
87
- case 1:
88
- _a.sent();
89
- if (silent)
90
- return [2 /*return*/];
91
- return [4 /*yield*/, this.parent.save()];
92
- case 2:
93
- _a.sent();
94
- return [2 /*return*/];
95
- }
96
- });
97
- });
98
- };
99
- Occurrence.prototype.sync = function () {
100
- return tslib.__awaiter(this, void 0, void 0, function () {
101
- return tslib.__generator(this, function (_a) {
102
- return [2 /*return*/, this.parent ? this.parent.sync() : _super.prototype.sync.call(this)];
103
- });
104
- });
105
- };
106
- /**
107
- * Returns a clean (no observables) JSON representation of the model.
108
- */
109
- Occurrence.prototype.toJSON = function () {
110
- var _a;
111
- var data = _super.prototype.toJSON.call(this);
112
- return JSON.parse(JSON.stringify(tslib.__assign(tslib.__assign({}, data), { media: ((_a = this.media) === null || _a === void 0 ? void 0 : _a.map(function (model) { return model.toJSON(); })) || [], metadata: mobx.toJS(this.metadata) || {} })));
113
- };
114
- Occurrence.prototype.getSurvey = function () {
115
- if (!this.parent)
116
- return {};
117
- var survey = this.parent.getSurvey();
118
- return survey.occ || {};
119
- };
120
- Occurrence.prototype.isUploaded = function () {
121
- if (!this.parent) {
122
- throw new Error('No occurrence parent to return disabled status.');
123
- }
124
- return this.parent.isUploaded();
125
- };
126
- Occurrence.prototype.isDisabled = function () {
127
- return this.isUploaded();
128
- };
129
- /**
130
- * Returns an object with attributes and their values
131
- * mapped for warehouse submission.
132
- */
133
- Occurrence.prototype.getSubmission = function (warehouseMediaNames) {
134
- var _this = this;
135
- if (warehouseMediaNames === void 0) { warehouseMediaNames = {}; }
136
- var occKeys = typeof this.keys === 'function' ? this.keys() : this.keys;
137
- var keys = tslib.__assign(tslib.__assign({}, Occurrence.keys), occKeys); // warehouse keys/values to transform
138
- var submission = {
139
- values: {
140
- external_key: this.cid,
141
- },
142
- media: [],
143
- };
144
- if (this.id) {
145
- submission.values.id = this.id;
146
- }
147
- var mapValue = function (attr, value) {
148
- var valuesMapping = keys[attr].values;
149
- if (!valuesMapping) {
150
- return value;
151
- }
152
- if (typeof valuesMapping === 'function') {
153
- return valuesMapping(value, submission, _this);
154
- }
155
- if (valuesMapping instanceof Array) {
156
- var mapping = valuesMapping.find(function (_a) {
157
- var val = _a.value;
158
- return val === value;
159
- });
160
- if (!mapping || !mapping.id) {
161
- throw new Error("A \"".concat(attr, "\" attribute \"").concat(value, "\" value could not be mapped to a remote database field."));
162
- }
163
- return mapping.id;
164
- }
165
- if (value instanceof Array) {
166
- return value.map(function (v) { return valuesMapping[v]; });
167
- }
168
- return valuesMapping[value];
169
- };
170
- var getValue = function (attr) {
171
- // no need to send attributes with no values
172
- var value = _this.attrs[attr];
173
- var isEmpty = function (val) { return val === null || val === undefined; };
174
- if (isEmpty(value)) {
175
- return;
176
- }
177
- if (!keys[attr]) {
178
- attr = attr.includes('occAttr:') ? attr : lodash.snakeCase(attr);
179
- submission.values[attr] = value;
180
- return;
181
- }
182
- var warehouseAttr = keys[attr].id || attr;
183
- value = mapValue(attr, value);
184
- if (isEmpty(value)) {
185
- return;
186
- }
187
- var attrKey = !Number.isNaN(Number(warehouseAttr))
188
- ? "occAttr:".concat(warehouseAttr)
189
- : warehouseAttr;
190
- attrKey = attrKey.includes('occAttr:') ? attrKey : lodash.snakeCase(attrKey);
191
- submission.values[attrKey] = value;
192
- };
193
- Object.keys(this.attrs).forEach(getValue);
194
- this.media.forEach(function (model) {
195
- var modelSubmission = model.getSubmission(warehouseMediaNames);
196
- if (!modelSubmission) {
197
- return;
198
- }
199
- submission.media.push(modelSubmission);
200
- });
201
- var survey = this.getSurvey();
202
- if (survey.modifySubmission) {
203
- return survey.modifySubmission(submission, this);
204
- }
205
- return submission;
206
- };
207
- /**
208
- * Warehouse attributes and their values.
209
- */
210
- Occurrence.keys = {
211
- taxon: { id: 'taxa_taxon_list_id' },
212
- training: { id: 'training', values: helpers.boolToWarehouseValue },
213
- deleted: { id: 'deleted', values: helpers.boolToWarehouseValue },
214
- confidential: { id: 'confidential', values: helpers.boolToWarehouseValue },
215
- zeroAbundance: { id: 'zero_abundance', values: helpers.boolToWarehouseValue },
216
- };
217
- return Occurrence;
218
- }(Model["default"]));
219
-
220
- exports["default"] = Occurrence;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),a=require("lodash"),n=require("../Model.js"),i=require("./Media.js"),r=require("./helpers.js"),o=function(n){function o(a){void 0===a&&(a={});var r=this,s=a.metadata,d=void 0===s?{}:s,u=a.media,c=void 0===u?[]:u,l=a.Media,p=void 0===l?i.default:l,v=e.__rest(a,["metadata","media","Media"]);v.createdAt=v.createdAt||(null==d?void 0:d.createdOn),v.updatedAt=v.updatedAt||(null==d?void 0:d.updatedOn),v.syncedAt=v.syncedAt||(null==d?void 0:d.syncedOn),(r=n.call(this,v)||this).debouncedValue=300,r.keys=function(){var t;return e.__assign(e.__assign({},o.keys),(t=r.getSurvey().attrs||{},Object.keys(t).reduce((function(a,n){var i;return e.__assign(e.__assign({},a),((i={})[n]=t[n].remote||t[n],i))}),{})))},r.Media=p,r.metadata=t.observable(d);var m,f,_=c.map((m=r.Media,void 0===f&&(f={}),function(t){return t instanceof m?t:new m(e.__assign(e.__assign({},t),f))}));r.media=t.observable(_);var h=function(e){return e.parent=r};r.media.forEach(h);return t.intercept(r.media,(function(e){var t;return(null===(t=e.added)||void 0===t?void 0:t.length)?(e.added.forEach(h),r.setUpdatedAtTimestamp(Date.now())):e.removedCount&&r.setUpdatedAtTimestamp(Date.now()),e})),r}return e.__extends(o,n),o.parseRemoteJSON=function(t,a,n){var i,o,s,d,u,c,l,p=t.id,v=t.metadata,m=t.event,f=t.occurrence,_=t.taxon,h=new Date(v.created_on).getTime(),y=new Date(v.updated_on).getTime(),b=Date.now(),g=m.parent_event_id?null===(o=null===(i=n.smp)||void 0===i?void 0:i.occ)||void 0===o?void 0:o.attrs:null===(s=n.occ)||void 0===s?void 0:s.attrs;g||(g=(null===(u=null===(d=n.smp)||void 0===d?void 0:d.occ)||void 0===u?void 0:u.attrs)||(null===(c=n.occ)||void 0===c?void 0:c.attrs)||{});var A=r.parseRemoteAttrs(g,f.attributes||[]),w=null===(l=f.media)||void 0===l?void 0:l.map((function(e){var t=e.path;return{id:t,createdAt:h,updatedAt:y,syncedAt:b,data:{data:"".concat(a,"/upload/").concat(t)}}})),N=_.species||_.taxon_name,x=N!==_.taxon_name?_.taxon_name:"";return{id:p,cid:p,createdAt:h,updatedAt:y,syncedAt:b,data:e.__assign(e.__assign({},A),{taxon:{warehouse_id:parseInt(_.taxa_taxon_list_id,10),scientific_name:N,scientificName:N,common_name:x,commonName:x,found_in_name:x?"common_name":"scientific_name",foundInName:x?"commonName":"scientificName"},comment:f.occurrence_remarks}),media:w}},o.prototype.setUpdatedAtTimestamp=function(e){var t;n.prototype.setUpdatedAtTimestamp.call(this,e),null===(t=this.parent)||void 0===t||t.setUpdatedAtTimestamp(e)},o.prototype.save=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){if(!this.parent)throw new Error("Trying to save locally without a parent");return this.parent.save(),[2]}))}))},o.prototype.destroy=function(t){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.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(e){return e.destroy(!0)})))];case 1:return e.sent(),t?[2]:[4,this.parent.save()];case 2:return e.sent(),[2]}}))}))},o.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)]}))}))},o.prototype.toJSON=function(){var a,i=n.prototype.toJSON.call(this);return JSON.parse(JSON.stringify(e.__assign(e.__assign({},i),{media:(null===(a=this.media)||void 0===a?void 0:a.map((function(e){return e.toJSON()})))||[],metadata:t.toJS(this.metadata)||{}})))},o.prototype.getSurvey=function(){return this.parent&&this.parent.getSurvey().occ||{}},Object.defineProperty(o.prototype,"isUploaded",{get:function(){if(!this.parent)throw new Error("No occurrence parent to return disabled status.");return this.parent.isUploaded},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"isDisabled",{get:function(){return this.isUploaded},enumerable:!1,configurable:!0}),o.prototype.getSubmission=function(t){var n=this;void 0===t&&(t={});var i="function"==typeof this.keys?this.keys():this.keys,r=e.__assign(e.__assign({},o.keys),i),s={values:{external_key:this.cid},media:[]};this.id&&(s.values.id=this.id);Object.keys(this.data).forEach((function(e){var t=n.data[e],i=function(e){return null==e};if(!i(t)){if(!r[e])return e=e.includes("occAttr:")?e:a.snakeCase(e),void(s.values[e]=t);var o=r[e].id||e;if(t=function(e,t){var a=r[e].values;if(!a)return t;if("function"==typeof a)return a(t,s,n);if(a instanceof Array){var i=a.find((function(e){return e.value===t}));if(!i||!i.id)throw new Error('A "'.concat(e,'" attribute "').concat(t,'" value could not be mapped to a remote database field.'));return i.id}return t instanceof Array?t.map((function(e){return a[e]})):a[t]}(e,t),!i(t)){var d=Number.isNaN(Number(o))?o:"occAttr:".concat(o);d=d.includes("occAttr:")?d:a.snakeCase(d),s.values[d]=t}}})),this.media.forEach((function(e){var a=e.getSubmission(t);a&&s.media.push(a)}));var d=this.getSurvey();return d.modifySubmission?d.modifySubmission(s,this):s},o.keys={taxon:{id:"taxa_taxon_list_id"},training:{id:"training",values:r.boolToWarehouseValue},deleted:{id:"deleted",values:r.boolToWarehouseValue},confidential:{id:"confidential",values:r.boolToWarehouseValue},zeroAbundance:{id:"zero_abundance",values:r.boolToWarehouseValue}},o}(n.default);exports.default=o;
@@ -1,5 +1,6 @@
1
1
  import { IObservableArray } from 'mobx';
2
- import Model, { Attrs as AttrsOriginal, Options as OptionsOriginal } from '../Model';
2
+ import Model, { Data as DataOriginal, Options as OptionsOriginal } from '../Model';
3
+ import ElasticSample from './ElasticSample';
3
4
  import Media from './Media';
4
5
  import Occurrence from './Occurrence';
5
6
  import { RemoteConfig, Keys } from './helpers';
@@ -17,8 +18,16 @@ export interface Options<T = any, S = any> extends OptionsOriginal<T> {
17
18
  occurrences?: any[];
18
19
  samples?: any[];
19
20
  media?: any[];
21
+ Sample?: typeof Sample<any, any>;
22
+ Occurrence?: typeof Occurrence<any, any>;
23
+ Media?: typeof Media<any, any>;
24
+ skipStore?: boolean;
20
25
  }
21
- export interface Attrs extends AttrsOriginal {
26
+ export interface Data extends DataOriginal {
27
+ /**
28
+ * Flag whether the Sample was deleted. Global and persistent models might not need this.
29
+ */
30
+ deleted?: boolean;
22
31
  surveyId?: string | number | null;
23
32
  /**
24
33
  * Remote website survey edit page path.
@@ -39,7 +48,7 @@ export interface Attrs extends AttrsOriginal {
39
48
  export interface Remote {
40
49
  synchronising?: boolean;
41
50
  url?: string | null;
42
- headers?: any;
51
+ getAccessToken: () => Promise<string>;
43
52
  timeout?: number;
44
53
  /**
45
54
  * @deprecated
@@ -62,9 +71,32 @@ export interface Survey extends BaseSurvey {
62
71
  smp?: Survey;
63
72
  occ?: BaseSurvey;
64
73
  }
65
- declare class Sample<T extends Attrs = Attrs, S extends Metadata = Metadata> extends Model<T> {
66
- static fromJSON(jsonProp: any, OccurrenceClass?: any, Sample?: any, // eslint-disable-line
67
- MediaClass?: any): Sample<Attrs, Metadata>;
74
+ declare class Sample<T extends Data = Data, S extends Metadata = Metadata> extends Model<T> {
75
+ /**
76
+ * Transform ES document into local structure.
77
+ */
78
+ static parseRemoteJSON({ id, event, location, metadata }: ElasticSample, remoteUrl: string, survey?: any): {
79
+ id: string;
80
+ cid: string;
81
+ createdAt: number;
82
+ updatedAt: number;
83
+ syncedAt: number;
84
+ metadata: {
85
+ saved: boolean;
86
+ };
87
+ data: any;
88
+ media: {
89
+ id: string;
90
+ metadata: {
91
+ updatedOn: Date;
92
+ createdOn: Date;
93
+ syncedOn: Date;
94
+ };
95
+ data: {
96
+ data: string;
97
+ };
98
+ }[] | undefined;
99
+ };
68
100
  /**
69
101
  * Warehouse attributes and their values.
70
102
  */
@@ -93,6 +125,9 @@ declare class Sample<T extends Attrs = Attrs, S extends Metadata = Metadata> ext
93
125
  values: (val?: boolean | "t" | "f" | null) => "t" | "f";
94
126
  };
95
127
  };
128
+ Sample: typeof Sample<any, any>;
129
+ Occurrence: typeof Occurrence<any, any>;
130
+ Media: typeof Media<any, any>;
96
131
  /**
97
132
  * Model persistent observable metadata.
98
133
  */
@@ -107,10 +142,18 @@ declare class Sample<T extends Attrs = Attrs, S extends Metadata = Metadata> ext
107
142
  occurrences: IObservableArray<Occurrence>;
108
143
  media: IObservableArray<Media>;
109
144
  parent?: Sample<T, S>;
110
- survey?: Survey;
145
+ private survey?;
111
146
  debouncedValue: number;
112
- constructor({ metadata, samples, occurrences, media, attrs, ...options }?: Options);
113
- setupdatedAtTimestamp(newUpdatedAt: number): void;
147
+ constructor({ metadata, samples, occurrences, media, Sample: SampleClass, Occurrence: OccurrenceClass, Media: MediaClass, skipStore, ...options }?: Options);
148
+ get isStored(): import("..").IStore<{
149
+ id?: string;
150
+ cid: string;
151
+ data: T;
152
+ createdAt: number;
153
+ updatedAt: number;
154
+ syncedAt?: number | null;
155
+ }> | undefined;
156
+ setUpdatedAtTimestamp(newUpdatedAt: number): void;
114
157
  /**
115
158
  * Returns a clean (no observables) JSON representation of the model.
116
159
  */
@@ -134,7 +177,7 @@ declare class Sample<T extends Attrs = Attrs, S extends Metadata = Metadata> ext
134
177
  private putRemote;
135
178
  private uploadMedia;
136
179
  getSubmission(warehouseMediaNames?: {}): any;
137
- isUploaded(): boolean;
138
- isDisabled(): boolean;
180
+ get isUploaded(): boolean;
181
+ get isDisabled(): boolean;
139
182
  }
140
183
  export default Sample;