@flumens/models 0.1.0 → 0.2.1

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.
@@ -0,0 +1,43 @@
1
+ import Deferred from '@flumens/utils/dist/deferred';
2
+ import ModelClass from './Model';
3
+ import Store from './Stores/Store';
4
+ interface ObservableArrayI<T> extends Array<T> {
5
+ new (...items: any[]): ObservableArrayI<any>;
6
+ name: string;
7
+ }
8
+ declare const ObservableArray: ObservableArrayI<any>;
9
+ export type Options<T extends ModelClass> = {
10
+ models?: T[];
11
+ id?: string;
12
+ cid?: string;
13
+ store?: Store;
14
+ Model?: any;
15
+ };
16
+ export default class Collection<T extends ModelClass> extends ObservableArray {
17
+ /**
18
+ * Remote server collection ID.
19
+ */
20
+ id?: string;
21
+ /**
22
+ * Key name of the collection used to save and fetch the model from locally.
23
+ */
24
+ cid?: string;
25
+ /**
26
+ * The offline store used to save and fetch the model from.
27
+ */
28
+ protected store?: Store;
29
+ /**
30
+ * A promise to flag if all the models were initialised from the store.
31
+ */
32
+ readonly ready: Deferred<boolean>;
33
+ readonly Model: new (args: any) => T;
34
+ constructor({ id, cid, models, store, Model }: Options<T>);
35
+ fetch: () => Promise<void>;
36
+ reset: () => Promise<void>;
37
+ spliceWithArray(...args: any): T[];
38
+ clear(): T[];
39
+ replace(...args: any): T[];
40
+ remove(...args: any): boolean;
41
+ toJSON(): T[];
42
+ }
43
+ export {};
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("@flumens/utils/dist/deferred"),i=require("@flumens/utils/dist/uuid"),n=require("./Model.js");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=o(r),u=o(i),a=function(t){function r(r){var i=r.id,o=r.cid,a=r.models,l=void 0===a?[]:a,d=r.store,c=r.Model,f=void 0===c?n.default:c,p=t.apply(this,l)||this;return p.ready=new s.default,p.fetch=function(){return e.__awaiter(p,void 0,void 0,(function(){var t,r,i,n=this;return e.__generator(this,(function(e){switch(e.label){case 0:return this.store&&this.Model?[4,this.store.findAll()]:(this.ready.resolve(!1),[2]);case 1:return t=e.sent(),r=function(e){return new n.Model(e)},i=t.map(r),this.push.apply(this,i),this.ready.resolve(!0),[2]}}))}))},p.reset=function(){return e.__awaiter(p,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.label){case 0:return this.length?[4,this.pop().destroy()]:[3,2];case 1:return e.sent(),[3,0];case 2:return[2]}}))}))},p.id=p.id||i,p.cid=p.cid||o||i||u.default(),p.Model=f,p.store=p.store||d,p}return e.__extends(r,t),r.prototype.spliceWithArray=function(){for(var e,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return(e=this).spliceWithArray.apply(e,t)},r.prototype.clear=function(){return this.clear()},r.prototype.replace=function(){for(var e,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return(e=this).replace.apply(e,t)},r.prototype.remove=function(){for(var e,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return(e=this).remove.apply(e,t)},r.prototype.toJSON=function(){return this.toJSON()},r}((function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return t.observable(e)}));exports.default=a;
@@ -1,5 +1,5 @@
1
1
  import { AnySchema } from 'yup';
2
- import Model, { Attrs as GenericModelAttrs, Options as GenericModelOptions } from './Model';
2
+ import Model, { Attrs as GenericModelAttrs, Options as GenericModelOptions } from '../Model';
3
3
  export type BackendConfig = {
4
4
  /**
5
5
  * Site URL without a trailing slash.
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("axios"),r=require("jwt-decode"),s=require("yup"),i=require("@flumens/utils/dist/errors"),n=require("../Model.js");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=a(t);function c(e,t){Object.keys(t).forEach((function(r){if(r.match(/^field_/)){var s=r.replace("field_","").replace(/_([a-z])/g,(function(e){return e[1].toUpperCase()}));if(!t[r])return;if(Array.isArray(t[r])&&t[r].length)return void(e[s]=t[r][0].value);e[s]=t[r]}}))}var u=function(e){var t;if(e.response&&e.response.data&&e.response.data.message){if(e.response.data.message.includes("is already taken"))throw new i.HandledError("This email is already taken.");if("The user credentials were incorrect."===e.response.data.message)throw new i.HandledError("Incorrect password or email");if("Unrecognized username or email address."===e.response.data.message)throw new i.HandledError("Unrecognized email address.");if("This account is already activated"===e.response.data.message)throw new i.HandledError("This account is already activated.");if(e.response.data.message.includes("not been activated"))throw new i.HandledError("The user has not been activated or is blocked.");throw new Error(e.response.data.message)}if(null===(t=e.message)||void 0===t?void 0:t.includes("timeout"))throw new i.HandledError("Timeout");throw e},h=6e4;var d={email:"",tokens:void 0,verified:!1,iss:void 0,indiciaUserId:void 0},l=function(t){function i(r){var i=this,a=r.config,o=e.__rest(r,["config"]);return(i=t.call(this,o)||this).attrs=n.default.extendAttrs(i.attrs,d),i.loginSchema=s.object().shape({email:s.string().email().required(),password:s.string().required()}),i.loginSchemaBackend=s.object().shape({id:s.number().required(),email:s.string().email().required()}),i.resetSchema=s.object().shape({email:s.string().email().required()}),i.registerSchema=s.object().shape({email:s.string().email().required(),password:s.string().required()}),i.registerSchemaBackend=s.object().shape({uid:s.array().of(s.object().shape({value:s.number().required()}))}),i.config=a,i}return e.__extends(i,t),i.prototype.logIn=function(t,r){return e.__awaiter(this,void 0,void 0,(function(){var s;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this._exchangePasswordToTokens(t,r)];case 1:return s=e.sent(),this.attrs.tokens=s,[4,this.refreshProfile()];case 2:return e.sent(),[2,this.save()]}}))}))},i.prototype.register=function(t,r,s){return e.__awaiter(this,void 0,void 0,(function(){var i,n,a,d;return e.__generator(this,(function(l){switch(l.label){case 0:return i=JSON.stringify(e.__assign({name:[{value:t}],pass:[{value:r}],mail:[{value:t}]},s)),n={method:"post",url:"".concat(this.config.url,"/user/register-with-password?_format=json"),headers:{"content-type":"application/json"},data:i,timeout:h},[4,o.default(n).catch(u)];case 1:return a=l.sent().data,[4,this.registerSchemaBackend.isValid(a)];case 2:if(!l.sent())throw new Error("Invalid backend response.");return[4,this._exchangePasswordToTokens(t,r)];case 3:return d=l.sent(),this.attrs.tokens=d,this.id=a.uid[0].value,this.attrs.email=t,c(this.attrs,a),[2,this.save()]}}))}))},i.prototype.reset=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s,i;return e.__generator(this,(function(e){switch(e.label){case 0:r=JSON.stringify({mail:t}),s={method:"post",url:"".concat(this.config.url,"/user/password?_format=json"),headers:{"content-type":"application/json"},data:r},e.label=1;case 1:return e.trys.push([1,3,,6]),[4,o.default(s).catch(u)];case 2:return e.sent(),[3,6];case 3:return"The user has not been activated or is blocked."!==(i=e.sent()).message?[3,5]:[4,this._sendVerificationEmail(t)];case 4:return e.sent(),[2];case 5:return u(i),[3,6];case 6:return[2]}}))}))},i.prototype.delete=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.getAccessToken(!0)];case 1:return t=e.sent(),r={method:"delete",url:"".concat(this.config.url,"/user/").concat(this.id,"?_format=json"),headers:{Authorization:"Bearer ".concat(t)}},[4,o.default(r).catch(u)];case 2:return e.sent(),this.logOut(),[2]}}))}))},i.prototype.refreshProfile=function(){return e.__awaiter(this,void 0,void 0,(function(){var t=this;return e.__generator(this,(function(r){return this._refreshingProfilePromise||(this._refreshingProfilePromise=Promise.resolve().then((function(){return e.__awaiter(t,void 0,void 0,(function(){var t,r,s;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.getAccessToken(!0)];case 1:return t=e.sent(),this.attrs.verified?(r={url:"".concat(this.config.url,"/user/").concat(this.id,"?_format=json"),headers:{Authorization:"Bearer ".concat(t)},timeout:h},[4,o.default(r).catch(u)]):[3,3];case 2:s=e.sent().data,this.attrs.email=s.mail[0].value,c(this.attrs,s),e.label=3;case 3:return[4,this.save()];case 4:return e.sent(),delete this._refreshingProfilePromise,[2]}}))}))})).catch((function(e){throw delete t._refreshingProfilePromise,e}))),[2,this._refreshingProfilePromise]}))}))},i.prototype.hasLogIn=function(){return console.warn("hasLogIn is deprecated, please use isLoggedIn instead."),this.isLoggedIn()},i.prototype.isLoggedIn=function(){return this.attrs.email,!!this.id},i.prototype.logOut=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,this.resetDefaults()]}))}))},i.prototype.resetDefaults=function(r){return t.prototype.resetDefaults.call(this,e.__assign(e.__assign({},d),r))},i.prototype.getAccessToken=function(t){var s;return e.__awaiter(this,void 0,void 0,(function(){var i,n,a,o,c;return e.__generator(this,(function(e){switch(e.label){case 0:if(!t&&!this.isLoggedIn())throw new Error("User is not logged in.");if(i=(this.attrs.tokens||{}).access_token,n=function(e){if(!e)return!0;var t=1e3*r.jwtDecode(e).exp;return Date.now()+12e4>t}(i),!(!i||n||t))return[3,6];e.label=1;case 1:return e.trys.push([1,3,,6]),[4,this._refreshAccessToken()];case 2:return e.sent(),[3,6];case 3:return a=e.sent(),console.error(a),o="The refresh token is invalid."===a.message,c="Token has no user email."===a.message,o||c?[4,this.logOut()]:[3,5];case 4:throw e.sent(),new Error("User re-login is required.");case 5:throw a;case 6:return[2,null===(s=this.attrs.tokens)||void 0===s?void 0:s.access_token]}}))}))},i.prototype._sendVerificationEmail=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s;return e.__generator(this,(function(e){return r=JSON.stringify({mail:[{value:t||this.attrs.email}]}),s={method:"post",url:"".concat(this.config.url,"/user/register-with-password?_format=json&resendVerificationEmail=true"),headers:{"content-type":"application/json"},data:r,timeout:h},[2,o.default(s).catch(u)]}))}))},i.prototype._exchangePasswordToTokens=function(t,r){var s;return e.__awaiter(this,void 0,void 0,(function(){var i,n;return e.__generator(this,(function(e){switch(e.label){case 0:return(i=new FormData).append("grant_type","password"),i.append("username",t),i.append("password",r),i.append("client_id",this.config.clientId),this.config.clientPass&&i.append("client_secret",this.config.clientPass),(null===(s=this.config.scopes)||void 0===s?void 0:s.length)&&i.append("scope",this.config.scopes.join(" ")),n={method:"post",url:"".concat(this.config.url,"/oauth/token"),data:i},[4,o.default(n).catch(u)];case 1:return[2,e.sent().data]}}))}))},i.prototype._refreshAccessToken=function(){return e.__awaiter(this,void 0,void 0,(function(){var t=this;return e.__generator(this,(function(s){return this._refreshingTokenPromise||(this._refreshingTokenPromise=Promise.resolve().then((function(){return e.__awaiter(t,void 0,void 0,(function(){var t,s,i,n,a,d;return e.__generator(this,(function(l){switch(l.label){case 0:if(!(t=(this.attrs.tokens||{}).refresh_token))throw new Error("No user session refresh token was found");return(s=new FormData).append("grant_type","refresh_token"),s.append("refresh_token",t),s.append("client_id",this.config.clientId),this.config.clientPass&&s.append("client_secret",this.config.clientPass),i={method:"post",url:"".concat(this.config.url,"/oauth/token"),data:s,timeout:h},[4,o.default(i).catch(u)];case 1:if(n=l.sent().data,this.attrs.tokens=e.__assign(e.__assign({},this.attrs.tokens),n),a=r.jwtDecode(null===(d=this.attrs.tokens)||void 0===d?void 0:d.access_token),this.id=a.sub,this.attrs.email=a.email,!this.attrs.email)throw new Error("Token has no user email.");return this.attrs.verified=a.email_verified,this.attrs.iss=a.iss,this.attrs.indiciaUserId=a["http://indicia.org.uk/user:id"],a.scopes&&(this.attrs.roles=a.scopes),c(this.attrs,a),[4,this.save()];case 2:return l.sent(),delete this._refreshingTokenPromise,[2]}}))}))})).catch((function(e){throw delete t._refreshingTokenPromise,e}))),[2,this._refreshingTokenPromise]}))}))},i}(n.default);exports.default=l;
@@ -131,6 +131,7 @@ declare class Sample<T extends Attrs = Attrs, S extends Metadata = Metadata> ext
131
131
  sync(): Promise<void>;
132
132
  requiresRemoteSync: () => boolean;
133
133
  saveRemote(): Promise<void>;
134
+ fetchRemote(): Promise<void>;
134
135
  updateRemote(): Promise<void>;
135
136
  private _createRemote;
136
137
  private _updateRemote;
@@ -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"),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(){var t;return e.__generator(this,(function(r){switch(r.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 t=this.toJSON(),[4,this._store.save(e.__assign(e.__assign({},t),{data:t.attrs}))];case 1:return r.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.delete(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;
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(){var t;return e.__generator(this,(function(r){switch(r.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 t=this.toJSON(),[4,this.store.save(e.__assign(e.__assign({},t),{data:t.attrs}))];case 1:return r.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.delete(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.fetchRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){throw new Error("Not implemented.")}))}))},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;
@@ -0,0 +1,18 @@
1
+ import Collection, { Options as CollectionOptions } from '../Collection';
2
+ import Store from '../Stores/Store';
3
+ import IndiciaSample from './Sample';
4
+ export type Options<T extends IndiciaSample> = {
5
+ models?: T[];
6
+ store?: Store;
7
+ Model?: typeof IndiciaSample<any, any>;
8
+ } & CollectionOptions<T>;
9
+ export default class SampleCollection<T extends IndiciaSample> extends Collection<T> {
10
+ constructor(options: Options<T>);
11
+ fetch: () => Promise<void>;
12
+ removeAllSynced: () => Promise<any[]>;
13
+ /**
14
+ * Reverse order so that newest are at the top of list.
15
+ */
16
+ comparator: (a: any) => number;
17
+ reset: () => Promise<void>;
18
+ }
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=function(r){function n(n){var o=r.call(this,n)||this;o.fetch=function(){return e.__awaiter(o,void 0,void 0,(function(){var t,r,n,o=this;return e.__generator(this,(function(i){switch(i.label){case 0:return this.store&&this.Model?[4,this.store.findAll()]:(this.ready.resolve(!1),[2]);case 1:return t=i.sent(),r=function(t){return o.Model.fromJSON(e.__assign(e.__assign({},t),{attrs:t.data}))},n=t.map(r),this.push.apply(this,n),this.ready.resolve(!0),[2]}}))}))},o.removeAllSynced=function(){var e=[];return o.forEach((function(t){t.syncedAt&&e.push(t.destroy())})),Promise.all(e)},o.comparator=function(e){return-new Date(e.createdAt).getTime()},o.reset=function(){return e.__awaiter(o,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]}}))}))};return t.observe(o,(function(e){e.addedCount&&e.added.forEach((function(e){return e.collection=o})),e.removedCount&&e.removed.forEach((function(e){return delete e.collection}))})),o}return e.__extends(n,r),n}(require("../Collection.js").default);exports.default=r;
package/dist/Model.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import Deferred from '@flumens/utils/dist/deferred';
1
2
  import Store from './Stores/Store';
2
3
  export interface Options<T = any> {
3
4
  id?: string;
@@ -46,19 +47,18 @@ export default class Model {
46
47
  /**
47
48
  * The offline store used to save and fetch the model from.
48
49
  */
49
- protected _store?: Store;
50
+ protected store?: Store;
50
51
  /**
51
52
  * A deferred promise to flag if the model was initialised from the store.
52
53
  */
53
- ready?: Promise<boolean>;
54
+ readonly ready: Deferred<boolean>;
54
55
  protected debouncedValue: number;
55
56
  constructor({ id, cid, createdAt, updatedAt, syncedAt, attrs, store, }: Options);
56
57
  setUpdatedAtTimestamp(newUpdatedAt: number): void;
57
58
  /**
58
59
  * Initialize the model from store.
59
60
  */
60
- fetch(): Promise<boolean>;
61
- private _fetch;
61
+ fetch(): Promise<void>;
62
62
  /**
63
63
  * Save the model to the offline store.
64
64
  */
package/dist/Model.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),s=require("mobx-utils");function i(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var r=i(require("@flumens/utils/dist/uuid")),n={deleted:!1},a=function(){function i(i){var a=this,o=i.id,u=void 0===o?"":o,d=i.cid,c=void 0===d?"":d,h=i.createdAt,_=i.updatedAt,f=i.syncedAt,l=i.attrs,p=void 0===l?{}:l,v=i.store;this.debouncedValue=3e3,this.id=u,this.cid=c||u||r.default();var y,A,g=Date.now();this.createdAt=h||g,this.updatedAt=_||g,this.syncedAt=f,this.attrs=e.observable((y=t.__assign(t.__assign({},n),p),JSON.parse(JSON.stringify(y)))),this._store=v;s.deepObserve(this.attrs,(function(){a.updatedAt=Date.now(),function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];clearTimeout(A),A=setTimeout((function(){return a.sync.apply(a,t)}),a.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 s;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(s=t.sent())?[3,3]:[4,this.save()];case 2:return t.sent(),[2,!0];case 3:return s.id&&(this.id=s.id),s.cid&&(this.cid=s.cid),e.set(this.attrs,s.data),this.createdAt=s.createdAt,this.updatedAt=s.updatedAt,this.syncedAt=s.syncedAt,[2,!0]}}))}))},i.prototype.save=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(s){switch(s.label){case 0:if(!this._store)throw new Error("Trying to save locally without a store");return e=this.toJSON(),[4,this._store.save(t.__assign(t.__assign({},e),{data:e.attrs}))];case 1:return s.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.delete(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(s){var i=this;this.id="";var r=JSON.parse(JSON.stringify(t.__assign(t.__assign({},n),s)));e.set(this.attrs,r);var a=Object.keys(r);return Object.keys(this.attrs).forEach((function(t){a.includes(t)||(i.attrs[t]=null,delete i.attrs[t])})),this.save()},i.extendAttrs=function(s,i){return e.set(s,t.__assign(t.__assign({},i),s)),s},i}();exports.default=a;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),s=require("mobx-utils"),r=require("@flumens/utils/dist/deferred"),i=require("@flumens/utils/dist/uuid");function a(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var n=a(r),o=a(i),d={deleted:!1},u=function(){function r(r){var i=this,a=r.id,u=void 0===a?"":a,c=r.cid,h=void 0===c?"":c,l=r.createdAt,f=r.updatedAt,v=r.syncedAt,p=r.attrs,_=void 0===p?{}:p,y=r.store;this.ready=new n.default,this.debouncedValue=3e3,this.id=u,this.cid=h||u||o.default();var b,A,g=Date.now();this.createdAt=l||g,this.updatedAt=f||g,this.syncedAt=v,this.attrs=(b=t.__assign(t.__assign({},d),_),JSON.parse(JSON.stringify(b))),e.makeObservable(this,{createdAt:e.observable,updatedAt:e.observable,syncedAt:e.observable,attrs:e.observable}),this.store=y;s.deepObserve(this.attrs,(function(){i.updatedAt=Date.now(),function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];clearTimeout(A),A=setTimeout((function(){return i.sync.apply(i,t)}),i.debouncedValue)}()}))}return r.prototype.setUpdatedAtTimestamp=function(t){this.updatedAt=t},r.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),e.set(this.attrs,s.data),this.createdAt=s.createdAt,this.updatedAt=s.updatedAt,this.syncedAt=s.syncedAt,this.ready.resolve(!0),[2]}}))}))},r.prototype.save=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(s){switch(s.label){case 0:if(!this.store)throw new Error("Trying to save locally without a store");return e=this.toJSON(),[4,this.store.save(t.__assign(t.__assign({},e),{data:e.attrs}))];case 1:return s.sent(),[2]}}))}))},r.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]}}))}))},r.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]}}))}))},r.prototype.toJSON=function(){return{id:this.id,cid:this.cid,createdAt:this.createdAt,updatedAt:this.updatedAt,syncedAt:this.syncedAt,attrs:e.toJS(this.attrs)}},r.prototype.resetDefaults=function(s){var r=this;this.id="";var i=JSON.parse(JSON.stringify(t.__assign(t.__assign({},d),s)));e.set(this.attrs,i);var a=Object.keys(i);return Object.keys(this.attrs).forEach((function(t){a.includes(t)||(r.attrs[t]=null,delete r.attrs[t])})),this.save()},r.extendAttrs=function(s,r){return e.set(s,t.__assign(t.__assign({},r),s)),s},r}();exports.default=u;
@@ -17,7 +17,7 @@ export default class SQLiteDatabase {
17
17
  protected name: string;
18
18
  protected debug: boolean;
19
19
  protected isWeb: boolean;
20
- ready: Deferred<boolean>;
20
+ readonly ready: Deferred<boolean>;
21
21
  constructor({ name, debug, web }: SQLiteDatabaseOptions);
22
22
  init(): Promise<void>;
23
23
  query<T>({ sql, params }: Query): Promise<T[]>;
@@ -1,8 +1,9 @@
1
- import { BuildColumns, ColumnBuilderBase, ColumnBuilderBaseConfig, ColumnDataType, InferModelFromColumns } from 'drizzle-orm';
2
- import { SQLiteSelect, SQLiteDelete } from 'drizzle-orm/sqlite-core';
1
+ import { BuildColumns, ColumnBuilderBase, ColumnBuilderBaseConfig, ColumnDataType, InferModelFromColumns, SQL } from 'drizzle-orm';
2
+ import { SQLiteSelect, SQLiteDelete, SQLiteTable } from 'drizzle-orm/sqlite-core';
3
3
  import Deferred from '@flumens/utils/dist/deferred';
4
4
  import SQLiteDatabase from './SQLiteDatabase';
5
5
  import Store from './Store';
6
+ export declare function conflictUpdateAllExcept<T extends SQLiteTable, E extends (keyof T['$inferInsert'])[]>(table: T, except: E): Omit<Record<string | number, SQL<unknown>>, E[number]>;
6
7
  export declare const jsonb: <TData>(name: string) => import("drizzle-orm/sqlite-core").SQLiteCustomColumnBuilder<{
7
8
  name: string;
8
9
  dataType: "custom";
@@ -46,7 +47,7 @@ export default class SQLiteStore<T = DefaultCols> implements Store {
46
47
  readonly ready: Deferred<boolean>;
47
48
  constructor({ db, name, debug, columns, }: SQLiteStoreOptions);
48
49
  private init;
49
- save(values: T): Promise<void>;
50
+ save(values: T | T[]): Promise<void>;
50
51
  find(q: string | Partial<T> | SelectQueryFn): Promise<T>;
51
52
  findAll(q?: SelectQueryFn): Promise<T[]>;
52
53
  delete(q: string | Partial<T> | DeleteQueryFn): Promise<void>;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("drizzle-orm"),r=require("drizzle-orm/casing"),n=require("drizzle-orm/sqlite-core"),i=require("@flumens/utils/dist/deferred"),a=require("./utils.js");function s(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var o=s(i),u=function(t){return n.customType({dataType:function(){return"jsonb"},toDriver:function(t){return JSON.stringify(t)}})(t)},d=new n.SQLiteSyncDialect,c=function(){function i(t){var e=t.db,r=t.name,i=t.debug,a=t.columns,s=void 0===a?{id:n.text(),cid:n.text().primaryKey().notNull().default("id"),data:u("data").notNull(),createdAt:n.integer("created_at").notNull(),updatedAt:n.integer("updated_at").notNull(),syncedAt:n.integer("synced_at")}:a;this.ready=new o.default,this.db=e,this.name=r,this.debug=i||!1,this.table=n.sqliteTable(this.name,s),this.init()}return i.prototype.init=function(){return t.__awaiter(this,void 0,void 0,(function(){var e,r;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.db.ready];case 1:return t.sent(),e=function(t){return"".concat(t.name," ").concat(t.getSQLType()).concat(t.primary?" primary key":"").concat(t.notNull?" not null":"").concat(t.default?" default ".concat(t.default):"")},r=n.getTableConfig(this.table).columns.map(e).join(",\n"),[4,this.db.query({sql:"CREATE TABLE IF NOT EXISTS ".concat(this.name," (").concat(r,");")})];case 2:return t.sent(),this.ready.resolve(!0),[2]}}))}))},i.prototype.save=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,i,s;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),this.debug&&e.cid?[4,this.find({cid:e.cid})]:[3,3];case 2:r=t.sent(),a.printDiff(r,e,e.cid,this.name),t.label=3;case 3:return i=new n.SQLiteInsertBuilder(this.table,{},d).values(e),(s=this._getPrimaryCol())&&(i=i.onConflictDoUpdate({target:s,set:e})),[4,this.db.query(i.toSQL())];case 4:return t.sent(),[2]}}))}))},i.prototype.find=function(r){return t.__awaiter(this,void 0,void 0,(function(){var n,i=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),n=function(t){if("function"==typeof r)return r(t).limit(1);if("string"==typeof r){var n=i._getPrimaryCol();if(!n)throw new Error("Primary col is missing");return t.where(e.eq(n,r)).limit(1)}var a=Object.entries(r).map((function(t){var r=t[0],n=t[1];return e.eq(i.table[r],n)}));return t.where(e.and.apply(void 0,a)).limit(1)},[4,this.findAll(n)];case 2:return[2,t.sent()[0]]}}))}))},i.prototype.findAll=function(i){return t.__awaiter(this,void 0,void 0,(function(){var a,s,o,u=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),a=(new n.QueryBuilder).select().from(this.table),i&&(a=i(a)),[4,this.db.query(a.toSQL())];case 2:return s=t.sent(),o=function(t){return Object.entries(t).reduce((function(t,n){var i,a=n[0],s=n[1],o="jsonb"===(null===(i=e.getTableColumns(u.table)[a])||void 0===i?void 0:i.sqlName);return t[r.toCamelCase(a)]=o?JSON.parse(s):s,t}),{})},[2,s.map(o)]}}))}))},i.prototype.delete=function(r){return t.__awaiter(this,void 0,void 0,(function(){var n,i=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),n=function(t){if("function"==typeof r)return r(t);if("string"==typeof r){var n=i._getPrimaryCol();if(!n)throw new Error("Primary col is missing");return t.where(e.eq(n,r))}var a=Object.entries(r).map((function(t){var r=t[0],n=t[1];return e.eq(i.table[r],n)}));return t.where(e.and.apply(void 0,a))},[4,this.deleteAll(n)];case 2:return t.sent(),[2]}}))}))},i.prototype.deleteAll=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:return t.sent(),r=new n.SQLiteDeleteBase(this.table,{},d),e&&(r=e(r)),[4,this.db.query(r.toSQL())];case 2:return t.sent(),[2]}}))}))},i.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,{})]}}))}))},i.prototype.import=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n,i=this;return t.__generator(this,(function(a){switch(a.label){case 0:return[4,this.ready];case 1:return a.sent(),[4,this.deleteAll()];case 2:if(a.sent(),"object"!=typeof e)throw new Error("Invalid obj passed to store");return r=function(e){var r,n,i,a,s,o;if(!e.createdAt&&(null===(r=e.metadata)||void 0===r?void 0:r.createdOn)&&(e.createdAt=null===(n=e.metadata)||void 0===n?void 0:n.createdOn),!e.updatedAt&&(null===(i=e.metadata)||void 0===i?void 0:i.updatedOn)&&(e.updatedAt=null===(a=e.metadata)||void 0===a?void 0:a.updatedOn),!e.syncedAt&&(null===(s=e.metadata)||void 0===s?void 0:s.syncedOn)&&(e.syncedAt=null===(o=e.metadata)||void 0===o?void 0:o.syncedOn),e.samples){var u=e.id,d=e.cid,c=e.createdAt,l=e.updatedAt,f=e.syncedAt,h=t.__rest(e,["id","cid","createdAt","updatedAt","syncedAt"]);e={id:u,cid:d,createdAt:c,updatedAt:l,syncedAt:f,data:t.__assign({},h)}}return e},n=Object.entries(e).map((function(t){var e=t[1];return i.save(r(e))})),Promise.all(n),[2]}}))}))},i.prototype._getPrimaryCol=function(){return Object.values(e.getTableColumns(this.table)).find((function(t){return!!t.primary}))},i}();exports.default=c,exports.jsonb=u;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("drizzle-orm"),r=require("drizzle-orm/casing"),n=require("drizzle-orm/sqlite-core"),i=require("@flumens/utils/dist/deferred"),a=require("./utils.js");function s(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var o=s(i);function u(r,n){var i=e.getTableColumns(r);return Object.entries(i).filter((function(t){var e=t[0];return!n.includes(e)})).reduce((function(r,n){var i,a=n[0],s=n[1];return t.__assign(t.__assign({},r),((i={})[a]=e.sql.raw("excluded.".concat(s.name)),i))}),{})}var c=function(t){return n.customType({dataType:function(){return"jsonb"},toDriver:function(t){return JSON.stringify(t)}})(t)},d=new n.SQLiteSyncDialect,l=function(){function i(t){var e=t.db,r=t.name,i=t.debug,a=t.columns,s=void 0===a?{id:n.text(),cid:n.text().primaryKey().notNull().default("id"),data:c("data").notNull(),createdAt:n.integer("created_at").notNull(),updatedAt:n.integer("updated_at").notNull(),syncedAt:n.integer("synced_at")}:a;this.ready=new o.default,this.db=e,this.name=r,this.debug=i||!1,this.table=n.sqliteTable(this.name,s),this.init()}return i.prototype.init=function(){return t.__awaiter(this,void 0,void 0,(function(){var e,r;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.db.ready];case 1:return t.sent(),e=function(t){return"".concat(t.name," ").concat(t.getSQLType()).concat(t.primary?" primary key":"").concat(t.notNull?" not null":"").concat(t.default?" default ".concat(t.default):"")},r=n.getTableConfig(this.table).columns.map(e).join(",\n"),[4,this.db.query({sql:"CREATE TABLE IF NOT EXISTS ".concat(this.name," (").concat(r,");")})];case 2:return t.sent(),this.ready.resolve(!0),[2]}}))}))},i.prototype.save=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,i,s;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),this.debug&&e.cid?[4,this.find({cid:e.cid})]:[3,3];case 2:r=t.sent(),a.printDiff(r,e,e.cid,this.name),t.label=3;case 3:return i=new n.SQLiteInsertBuilder(this.table,{},d).values(e),(s=this._getPrimaryCol())&&(i=i.onConflictDoUpdate({target:s,set:u(this.table,[])})),[4,this.db.query(i.toSQL())];case 4:return t.sent(),[2]}}))}))},i.prototype.find=function(r){return t.__awaiter(this,void 0,void 0,(function(){var n,i=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),n=function(t){if("function"==typeof r)return r(t).limit(1);if("string"==typeof r){var n=i._getPrimaryCol();if(!n)throw new Error("Primary col is missing");return t.where(e.eq(n,r)).limit(1)}var a=Object.entries(r).map((function(t){var r=t[0],n=t[1];return e.eq(i.table[r],n)}));return t.where(e.and.apply(void 0,a)).limit(1)},[4,this.findAll(n)];case 2:return[2,t.sent()[0]]}}))}))},i.prototype.findAll=function(i){return t.__awaiter(this,void 0,void 0,(function(){var a,s,o,u=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),a=(new n.QueryBuilder).select().from(this.table),i&&(a=i(a)),[4,this.db.query(a.toSQL())];case 2:return s=t.sent(),o=function(t){return Object.entries(t).reduce((function(t,n){var i,a=n[0],s=n[1],o="jsonb"===(null===(i=e.getTableColumns(u.table)[a])||void 0===i?void 0:i.sqlName);return t[r.toCamelCase(a)]=o?JSON.parse(s):s,t}),{})},[2,s.map(o)]}}))}))},i.prototype.delete=function(r){return t.__awaiter(this,void 0,void 0,(function(){var n,i=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),n=function(t){if("function"==typeof r)return r(t);if("string"==typeof r){var n=i._getPrimaryCol();if(!n)throw new Error("Primary col is missing");return t.where(e.eq(n,r))}var a=Object.entries(r).map((function(t){var r=t[0],n=t[1];return e.eq(i.table[r],n)}));return t.where(e.and.apply(void 0,a))},[4,this.deleteAll(n)];case 2:return t.sent(),[2]}}))}))},i.prototype.deleteAll=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:return t.sent(),r=new n.SQLiteDeleteBase(this.table,{},d),e&&(r=e(r)),[4,this.db.query(r.toSQL())];case 2:return t.sent(),[2]}}))}))},i.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,{})]}}))}))},i.prototype.import=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n,i=this;return t.__generator(this,(function(a){switch(a.label){case 0:return[4,this.ready];case 1:return a.sent(),[4,this.deleteAll()];case 2:if(a.sent(),"object"!=typeof e)throw new Error("Invalid obj passed to store");return r=function(e){var r,n,i,a,s,o;if(!e.createdAt&&(null===(r=e.metadata)||void 0===r?void 0:r.createdOn)&&(e.createdAt=null===(n=e.metadata)||void 0===n?void 0:n.createdOn),!e.updatedAt&&(null===(i=e.metadata)||void 0===i?void 0:i.updatedOn)&&(e.updatedAt=null===(a=e.metadata)||void 0===a?void 0:a.updatedOn),!e.syncedAt&&(null===(s=e.metadata)||void 0===s?void 0:s.syncedOn)&&(e.syncedAt=null===(o=e.metadata)||void 0===o?void 0:o.syncedOn),e.samples){var u=e.id,c=e.cid,d=e.createdAt,l=e.updatedAt,f=e.syncedAt,h=t.__rest(e,["id","cid","createdAt","updatedAt","syncedAt"]);e={id:u,cid:c,createdAt:d,updatedAt:l,syncedAt:f,data:t.__assign({},h)}}return e},n=Object.entries(e).map((function(t){var e=t[1];return i.save(r(e))})),Promise.all(n),[2]}}))}))},i.prototype._getPrimaryCol=function(){return Object.values(e.getTableColumns(this.table)).find((function(t){return!!t.primary}))},i}();exports.conflictUpdateAllExcept=u,exports.default=l,exports.jsonb=c;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
package/dist/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- export { default as DrupalUserModel } from './DrupalUserModel';
2
- export { default as initStoredSamples } from './initStoredSamples';
1
+ export { default as DrupalUserModel } from './Drupal/User';
3
2
  export * from './Stores';
4
3
  export { default as Model } from './Model';
5
4
  export { default as Collection } from './Collection';
@@ -8,3 +7,4 @@ export { default as ElasticIndiciaOccurrence } from './Indicia/ElasticOccurrence
8
7
  export { default as ElasticIndiciaSample } from './Indicia/ElasticSample';
9
8
  export { default as IndiciaOccurrence } from './Indicia/Occurrence';
10
9
  export { default as IndiciaSample } from './Indicia/Sample';
10
+ export { default as IndiciaSampleCollection } from './Indicia/SampleCollection';
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/SQLiteDatabase.js"),i=require("./Stores/LocalForageStore.js"),o=require("./Stores/SQLiteStore.js"),a=require("./Stores/Store.js"),s=require("./Model.js"),l=require("./Collection/index.js"),u=require("./Indicia/Media.js"),d=require("./Indicia/Occurrence.js"),S=require("./Indicia/Sample.js");exports.DrupalUserModel=e.default,exports.initStoredSamples=r.default,exports.SQLiteDatabase=t.default,exports.LocalForageStore=i.default,exports.SQLiteStore=o.default,exports.IStore=a.default,exports.Model=s.default,exports.Collection=l.default,exports.IndiciaMedia=u.default,exports.IndiciaOccurrence=d.default,exports.IndiciaSample=S.default;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./Drupal/User.js"),r=require("./Stores/SQLiteDatabase.js"),t=require("./Stores/LocalForageStore.js"),a=require("./Stores/SQLiteStore.js"),i=require("./Stores/Store.js"),o=require("./Model.js"),s=require("./Collection.js"),l=require("./Indicia/Media.js"),u=require("./Indicia/Occurrence.js"),d=require("./Indicia/Sample.js"),c=require("./Indicia/SampleCollection.js");exports.DrupalUserModel=e.default,exports.SQLiteDatabase=r.default,exports.LocalForageStore=t.default,exports.SQLiteStore=a.default,exports.IStore=i.default,exports.Model=o.default,exports.Collection=s.default,exports.IndiciaMedia=l.default,exports.IndiciaOccurrence=u.default,exports.IndiciaSample=d.default,exports.IndiciaSampleCollection=c.default;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flumens/models",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/src/index.d.ts",
6
6
  "scripts": {
@@ -1,43 +0,0 @@
1
- import Model from '../Model';
2
- import Store from '../Stores/Store';
3
-
4
- export default class Collection<T extends Model> extends Array<T> {
5
- /**
6
- * Remote server collection ID.
7
- */
8
- id?: string;
9
-
10
- /**
11
- * Key name of tdehe collection used to save and fetch the model from locally.
12
- */
13
- cid: string;
14
-
15
- /**
16
- * The offline store used to save and fetch the model from.
17
- */
18
- protected _store?: Store;
19
-
20
- /**
21
- * A promise to flag if all the models were initialised from the store.
22
- */
23
- ready?: Promise<boolean>;
24
-
25
- Model?: typeof Model;
26
-
27
- constructor(options: {
28
- models?: T[];
29
- id?: string;
30
- cid?: string;
31
- store?: Store;
32
- Model?: typeof Model;
33
- });
34
-
35
- private _fromStore(): Promise<boolean>;
36
-
37
- remove(model: T): any; // mobx
38
-
39
- /**
40
- * Reset whole collection to empty. Does delete the local cache from store.
41
- */
42
- reset(): Promise<void>;
43
- }
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("mobx");function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=t(require("@flumens/utils/dist/uuid"));const s={async reset(){for(;this.length;){const e=this.pop();if(!e)return;await e.destroy()}},async _fromStore(){if(!this._store||!this.Model)return!1;const e=(await this._store.findAll()).map((e=>new this.Model(e)));return this.push(...e),!0}};exports.default=function({models:t=[],id:o="",cid:i="",store:n,Model:u}){const d=e.observable([...t]);return Object.assign(d,s,{_store:n,Model:u}),d.id=o,d.cid=i||o||r.default(),d.ready=d._fromStore(),d};
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("axios"),r=require("jwt-decode"),s=require("yup"),i=require("@flumens/utils/dist/errors"),n=require("./Model.js");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=a(t);function c(e,t){Object.keys(t).forEach((function(r){if(r.match(/^field_/)){var s=r.replace("field_","").replace(/_([a-z])/g,(function(e){return e[1].toUpperCase()}));if(!t[r])return;if(Array.isArray(t[r])&&t[r].length)return void(e[s]=t[r][0].value);e[s]=t[r]}}))}var u=function(e){var t;if(e.response&&e.response.data&&e.response.data.message){if(e.response.data.message.includes("is already taken"))throw new i.HandledError("This email is already taken.");if("The user credentials were incorrect."===e.response.data.message)throw new i.HandledError("Incorrect password or email");if("Unrecognized username or email address."===e.response.data.message)throw new i.HandledError("Unrecognized email address.");if("This account is already activated"===e.response.data.message)throw new i.HandledError("This account is already activated.");if(e.response.data.message.includes("not been activated"))throw new i.HandledError("The user has not been activated or is blocked.");throw new Error(e.response.data.message)}if(null===(t=e.message)||void 0===t?void 0:t.includes("timeout"))throw new i.HandledError("Timeout");throw e},h=6e4;var d={email:"",tokens:void 0,verified:!1,iss:void 0,indiciaUserId:void 0},l=function(t){function i(r){var i=this,a=r.config,o=e.__rest(r,["config"]);return(i=t.call(this,o)||this).attrs=n.default.extendAttrs(i.attrs,d),i.loginSchema=s.object().shape({email:s.string().email().required(),password:s.string().required()}),i.loginSchemaBackend=s.object().shape({id:s.number().required(),email:s.string().email().required()}),i.resetSchema=s.object().shape({email:s.string().email().required()}),i.registerSchema=s.object().shape({email:s.string().email().required(),password:s.string().required()}),i.registerSchemaBackend=s.object().shape({uid:s.array().of(s.object().shape({value:s.number().required()}))}),i.config=a,i}return e.__extends(i,t),i.prototype.logIn=function(t,r){return e.__awaiter(this,void 0,void 0,(function(){var s;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this._exchangePasswordToTokens(t,r)];case 1:return s=e.sent(),this.attrs.tokens=s,[4,this.refreshProfile()];case 2:return e.sent(),[2,this.save()]}}))}))},i.prototype.register=function(t,r,s){return e.__awaiter(this,void 0,void 0,(function(){var i,n,a,d;return e.__generator(this,(function(l){switch(l.label){case 0:return i=JSON.stringify(e.__assign({name:[{value:t}],pass:[{value:r}],mail:[{value:t}]},s)),n={method:"post",url:"".concat(this.config.url,"/user/register-with-password?_format=json"),headers:{"content-type":"application/json"},data:i,timeout:h},[4,o.default(n).catch(u)];case 1:return a=l.sent().data,[4,this.registerSchemaBackend.isValid(a)];case 2:if(!l.sent())throw new Error("Invalid backend response.");return[4,this._exchangePasswordToTokens(t,r)];case 3:return d=l.sent(),this.attrs.tokens=d,this.id=a.uid[0].value,this.attrs.email=t,c(this.attrs,a),[2,this.save()]}}))}))},i.prototype.reset=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s,i;return e.__generator(this,(function(e){switch(e.label){case 0:r=JSON.stringify({mail:t}),s={method:"post",url:"".concat(this.config.url,"/user/password?_format=json"),headers:{"content-type":"application/json"},data:r},e.label=1;case 1:return e.trys.push([1,3,,6]),[4,o.default(s).catch(u)];case 2:return e.sent(),[3,6];case 3:return"The user has not been activated or is blocked."!==(i=e.sent()).message?[3,5]:[4,this._sendVerificationEmail(t)];case 4:return e.sent(),[2];case 5:return u(i),[3,6];case 6:return[2]}}))}))},i.prototype.delete=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.getAccessToken(!0)];case 1:return t=e.sent(),r={method:"delete",url:"".concat(this.config.url,"/user/").concat(this.id,"?_format=json"),headers:{Authorization:"Bearer ".concat(t)}},[4,o.default(r).catch(u)];case 2:return e.sent(),this.logOut(),[2]}}))}))},i.prototype.refreshProfile=function(){return e.__awaiter(this,void 0,void 0,(function(){var t=this;return e.__generator(this,(function(r){return this._refreshingProfilePromise||(this._refreshingProfilePromise=Promise.resolve().then((function(){return e.__awaiter(t,void 0,void 0,(function(){var t,r,s;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.getAccessToken(!0)];case 1:return t=e.sent(),this.attrs.verified?(r={url:"".concat(this.config.url,"/user/").concat(this.id,"?_format=json"),headers:{Authorization:"Bearer ".concat(t)},timeout:h},[4,o.default(r).catch(u)]):[3,3];case 2:s=e.sent().data,this.attrs.email=s.mail[0].value,c(this.attrs,s),e.label=3;case 3:return[4,this.save()];case 4:return e.sent(),delete this._refreshingProfilePromise,[2]}}))}))})).catch((function(e){throw delete t._refreshingProfilePromise,e}))),[2,this._refreshingProfilePromise]}))}))},i.prototype.hasLogIn=function(){return console.warn("hasLogIn is deprecated, please use isLoggedIn instead."),this.isLoggedIn()},i.prototype.isLoggedIn=function(){return this.attrs.email,!!this.id},i.prototype.logOut=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,this.resetDefaults()]}))}))},i.prototype.resetDefaults=function(r){return t.prototype.resetDefaults.call(this,e.__assign(e.__assign({},d),r))},i.prototype.getAccessToken=function(t){var s;return e.__awaiter(this,void 0,void 0,(function(){var i,n,a,o,c;return e.__generator(this,(function(e){switch(e.label){case 0:if(!t&&!this.isLoggedIn())throw new Error("User is not logged in.");if(i=(this.attrs.tokens||{}).access_token,n=function(e){if(!e)return!0;var t=1e3*r.jwtDecode(e).exp;return Date.now()+12e4>t}(i),!(!i||n||t))return[3,6];e.label=1;case 1:return e.trys.push([1,3,,6]),[4,this._refreshAccessToken()];case 2:return e.sent(),[3,6];case 3:return a=e.sent(),console.error(a),o="The refresh token is invalid."===a.message,c="Token has no user email."===a.message,o||c?[4,this.logOut()]:[3,5];case 4:throw e.sent(),new Error("User re-login is required.");case 5:throw a;case 6:return[2,null===(s=this.attrs.tokens)||void 0===s?void 0:s.access_token]}}))}))},i.prototype._sendVerificationEmail=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s;return e.__generator(this,(function(e){return r=JSON.stringify({mail:[{value:t||this.attrs.email}]}),s={method:"post",url:"".concat(this.config.url,"/user/register-with-password?_format=json&resendVerificationEmail=true"),headers:{"content-type":"application/json"},data:r,timeout:h},[2,o.default(s).catch(u)]}))}))},i.prototype._exchangePasswordToTokens=function(t,r){var s;return e.__awaiter(this,void 0,void 0,(function(){var i,n;return e.__generator(this,(function(e){switch(e.label){case 0:return(i=new FormData).append("grant_type","password"),i.append("username",t),i.append("password",r),i.append("client_id",this.config.clientId),this.config.clientPass&&i.append("client_secret",this.config.clientPass),(null===(s=this.config.scopes)||void 0===s?void 0:s.length)&&i.append("scope",this.config.scopes.join(" ")),n={method:"post",url:"".concat(this.config.url,"/oauth/token"),data:i},[4,o.default(n).catch(u)];case 1:return[2,e.sent().data]}}))}))},i.prototype._refreshAccessToken=function(){return e.__awaiter(this,void 0,void 0,(function(){var t=this;return e.__generator(this,(function(s){return this._refreshingTokenPromise||(this._refreshingTokenPromise=Promise.resolve().then((function(){return e.__awaiter(t,void 0,void 0,(function(){var t,s,i,n,a,d;return e.__generator(this,(function(l){switch(l.label){case 0:if(!(t=(this.attrs.tokens||{}).refresh_token))throw new Error("No user session refresh token was found");return(s=new FormData).append("grant_type","refresh_token"),s.append("refresh_token",t),s.append("client_id",this.config.clientId),this.config.clientPass&&s.append("client_secret",this.config.clientPass),i={method:"post",url:"".concat(this.config.url,"/oauth/token"),data:s,timeout:h},[4,o.default(i).catch(u)];case 1:if(n=l.sent().data,this.attrs.tokens=e.__assign(e.__assign({},this.attrs.tokens),n),a=r.jwtDecode(null===(d=this.attrs.tokens)||void 0===d?void 0:d.access_token),this.id=a.sub,this.attrs.email=a.email,!this.attrs.email)throw new Error("Token has no user email.");return this.attrs.verified=a.email_verified,this.attrs.iss=a.iss,this.attrs.indiciaUserId=a["http://indicia.org.uk/user:id"],a.scopes&&(this.attrs.roles=a.scopes),c(this.attrs,a),[4,this.save()];case 2:return l.sent(),delete this._refreshingTokenPromise,[2]}}))}))})).catch((function(e){throw delete t._refreshingTokenPromise,e}))),[2,this._refreshingTokenPromise]}))}))},i}(n.default);exports.default=l;
@@ -1,3 +0,0 @@
1
- import IndiciaSample from './Indicia/Sample';
2
- import Store from './Stores/Store';
3
- export default function initStoredSamples(store: Store, Sample: typeof IndiciaSample<any, any>): any;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),r=require("mobx");exports.default=function(t,n){var o=r.observable([]);return r.observe(o,(function(e){e.addedCount&&(e.added[0].collection=o)})),o.ready=t.findAll().then((function(r){return r.forEach((function(r){var t=n.fromJSON(e.__assign(e.__assign({},r),{attrs:r.data}));o.push(t)}))})),o.removeAllSynced=function(){var e=[];return o.forEach((function(r){r.syncedAt&&e.push(r.destroy())})),Promise.all(e)},o.comparator=function(e){return-new Date(e.createdAt).getTime()},o.resetDefaults=function(){var e=o.map((function(e){return e.destroy()}));return Promise.all(e)},o};