@flumens/models 0.24.0 → 0.25.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 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("axios"),i=require("jwt-decode"),s=require("zod"),r=require("@flumens/utils"),a=require("../Model.js");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=o(t);function d(e){const t={};return Object.keys(e).forEach((i=>{if(i.match(/^field_/)){const s=i.replace("field_","").replace(/_([a-z])/g,(e=>e[1].toUpperCase()));if(!e[i])return;if(Array.isArray(e[i])&&e[i].length)return void(t[s]=e[i][0].value);t[s]=e[i]}})),t}const c=e=>{var t;if(e.response&&e.response.data&&e.response.data.message){if(e.response.data.message.includes("is already taken"))throw new r.HandledError("This email is already taken.");if("The user credentials were incorrect."===e.response.data.message)throw new r.HandledError("Incorrect password or email");if("Unrecognized username or email address."===e.response.data.message)throw new r.HandledError("Unrecognized email address.");if("This account is already activated"===e.response.data.message)throw new r.HandledError("This account is already activated.");if(e.response.data.message.includes("not been activated"))throw new r.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 r.HandledError("Timeout");throw e},l=6e4;const h={email:"",tokens:void 0,verified:!1,iss:void 0,indiciaUserId:void 0,profileFetched:!1};class u extends a.default{constructor(t){var{config:i}=t,s=e.__rest(t,["config"]);super(Object.assign(Object.assign({},s),{data:Object.assign(Object.assign({},h),s.data)})),this.config=i}logIn(t,i){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this._exchangePasswordToTokens(t,i);return this.data.tokens=e,yield this.refreshProfile(),this.save()}))}register(t,i,s){return e.__awaiter(this,void 0,void 0,(function*(){const e=JSON.stringify(Object.assign({name:[{value:t}],pass:[{value:i}],mail:[{value:t}]},s)),r={method:"post",url:`${this.config.url}/user/register-with-password?_format=json`,headers:{"content-type":"application/json"},data:e,timeout:l},{data:a}=yield n.default(r).catch(c);if(!!u.registerSchemaBackend.safeParse(a).error)throw new Error("Invalid backend response.");const o=yield this._exchangePasswordToTokens(t,i);this.id=a.uid[0].value;const h=d(a);return Object.assign(this.data,Object.assign({email:t,tokens:o,profileFetched:!0},h)),this.save()}))}resetPassword(t){return e.__awaiter(this,void 0,void 0,(function*(){const e=JSON.stringify({mail:t}),i={method:"post",url:`${this.config.url}/user/password?_format=json`,headers:{"content-type":"application/json"},data:e};try{yield n.default(i).catch(c)}catch(e){if("The user has not been activated or is blocked."===e.message)return void(yield this._sendVerificationEmail(t));c(e)}}))}delete(){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(!0),t={method:"delete",url:`${this.config.url}/user/${this.id}?_format=json`,headers:{Authorization:`Bearer ${e}`}};yield n.default(t).catch(c),this.logOut()}))}updateRemote(t){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(),i={method:"patch",url:`${this.config.url}/user/${this.id}?_format=json`,data:t,headers:{Authorization:`Bearer ${e}`},timeout:l};yield n.default(i),yield this._refreshAccessToken(),this.save()}))}refreshProfile(){return e.__awaiter(this,void 0,void 0,(function*(){return this._refreshingProfilePromise||(this._refreshingProfilePromise=Promise.resolve().then((()=>e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(!0);if(this.data.verified){const t={url:`${this.config.url}/user/${this.id}?_format=json`,headers:{Authorization:`Bearer ${e}`},timeout:l},{data:i}=yield n.default(t).catch(c),s=d(i);Object.assign(this.data,Object.assign({email:i.mail[0].value,profileFetched:!0},s))}yield this.save(),delete this._refreshingProfilePromise})))).catch((e=>{throw delete this._refreshingProfilePromise,e}))),this._refreshingProfilePromise}))}hasLogIn(){return console.warn("hasLogIn is deprecated, please use isLoggedIn instead."),this.isLoggedIn()}isLoggedIn(){return this.data.email,!!this.id}logOut(){return e.__awaiter(this,void 0,void 0,(function*(){return this.reset()}))}reset(e){return super.reset(Object.assign(Object.assign({},h),e))}getAccessToken(t){return e.__awaiter(this,void 0,void 0,(function*(){if(!t&&!this.isLoggedIn())throw new Error("User is not logged in.");const{access_token:e}=this.data.tokens||{},s=function(e){if(!e)return!0;const{exp:t}=i.jwtDecode(e),s=1e3*t;return Date.now()+12e4>s}(e);if(!e||s||t)try{yield this._refreshAccessToken()}catch(e){console.error(e);const t="The refresh token is invalid."===e.message,i="Token has no user email."===e.message;if(t||i)throw yield this.logOut(),new Error("User re-login is required.");throw e}return this.data.tokens.access_token}))}_sendVerificationEmail(t){return e.__awaiter(this,void 0,void 0,(function*(){const e=JSON.stringify({mail:[{value:t||this.data.email}]}),i={method:"post",url:`${this.config.url}/user/register-with-password?_format=json&resendVerificationEmail=true`,headers:{"content-type":"application/json"},data:e,timeout:l};return n.default(i).catch(c)}))}_exchangePasswordToTokens(t,i){return e.__awaiter(this,void 0,void 0,(function*(){var e;const s=new FormData;s.append("grant_type","password"),s.append("username",t),s.append("password",i),s.append("client_id",this.config.clientId),this.config.clientPass&&s.append("client_secret",this.config.clientPass),(null===(e=this.config.scopes)||void 0===e?void 0:e.length)&&s.append("scope",this.config.scopes.join(" "));const r={method:"post",url:`${this.config.url}/oauth/token`,data:s},{data:a}=yield n.default(r).catch(c);return a}))}_refreshAccessToken(){return e.__awaiter(this,void 0,void 0,(function*(){return this._refreshingTokenPromise||(this._refreshingTokenPromise=Promise.resolve().then((()=>e.__awaiter(this,void 0,void 0,(function*(){const{refresh_token:e}=this.data.tokens||{};if(!e)throw new Error("No user session refresh token was found");const t=new FormData;t.append("grant_type","refresh_token"),t.append("refresh_token",e),t.append("client_id",this.config.clientId),this.config.clientPass&&t.append("client_secret",this.config.clientPass);const s={method:"post",url:`${this.config.url}/oauth/token`,data:t,timeout:l},{data:r}=yield n.default(s).catch(c),a=Object.assign(Object.assign({},this.data.tokens),r),o=i.jwtDecode(a.access_token),{email:h}=o;if(!h)throw new Error("Token has no user email.");const{iss:u,email_verified:f}=o,g=o["http://indicia.org.uk/user:id"],m=o.scopes,p=d(o);this.id=o.sub,Object.assign(this.data,Object.assign({email:h,roles:m,verified:f,iss:u,indiciaUserId:g,tokens:a},p)),yield this.save(),delete this._refreshingTokenPromise})))).catch((e=>{throw delete this._refreshingTokenPromise,e}))),this._refreshingTokenPromise}))}}u.loginSchema=s.object({email:s.z.string().email("Please fill in"),password:s.z.string().min(1,"Please fill in")}),u.loginSchemaBackend=s.object({id:s.z.number(),email:s.z.string().email()}),u.resetSchema=s.object({email:s.z.string().email("Please fill in")}),u.registerSchema=s.object({email:s.z.string().email("Please fill in"),password:s.z.string().min(1,"Please fill in")}),u.registerSchemaBackend=s.object({uid:s.z.array(s.object({value:s.z.number()}))}),exports.default=u;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),i=require("axios"),t=require("jwt-decode"),s=require("zod"),r=require("@flumens/utils"),o=require("../Model.js");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var a=n(i);function d(e){const i={};return Object.keys(e).forEach((t=>{if(t.match(/^field_/)){const s=t.replace("field_","").replace(/_([a-z])/g,(e=>e[1].toUpperCase()));if(!e[t])return;if(Array.isArray(e[t])&&e[t].length)return void(i[s]=e[t][0].value);i[s]=e[t]}})),i}const c=e=>{var i,t,s,o,n;const a=(null===(t=null===(i=e.response)||void 0===i?void 0:i.data)||void 0===t?void 0:t.error_description)||(null===(o=null===(s=e.response)||void 0===s?void 0:s.data)||void 0===o?void 0:o.message);if(a){if(a.includes("is already taken"))throw new r.HandledError("This email is already taken.");if("The user credentials were incorrect."===a)throw new r.HandledError("Incorrect password or email");if("Unrecognized username or email address."===a)throw new r.HandledError("Unrecognized email address.");if("This account is already activated"===a)throw new r.HandledError("This account is already activated.");if(a.includes("not been activated"))throw new r.HandledError("The user has not been activated or is blocked.");throw new Error(a)}if(null===(n=e.message)||void 0===n?void 0:n.includes("timeout"))throw new r.HandledError("Timeout");throw e},l=6e4;const h={email:"",tokens:void 0,verified:!1,iss:void 0,indiciaUserId:void 0,profileFetched:!1};class u extends o.default{constructor(i){var{config:t}=i,s=e.__rest(i,["config"]);super(Object.assign(Object.assign({},s),{data:Object.assign(Object.assign({},h),s.data)})),this.config=t}logIn(i,t){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this._exchangePasswordToTokens(i,t);return this.data.tokens=e,yield this.refreshProfile(),this.save()}))}register(i,t,s){return e.__awaiter(this,void 0,void 0,(function*(){const e=JSON.stringify(Object.assign({name:[{value:i}],pass:[{value:t}],mail:[{value:i}]},s)),r={method:"post",url:`${this.config.url}/user/register-with-password?_format=json`,headers:{"content-type":"application/json"},data:e,timeout:l},{data:o}=yield a.default(r).catch(c);if(!!u.registerSchemaBackend.safeParse(o).error)throw new Error("Invalid backend response.");const n=yield this._exchangePasswordToTokens(i,t);this.id=o.uid[0].value;const h=d(o);return Object.assign(this.data,Object.assign({email:i,tokens:n,profileFetched:!0},h)),this.save()}))}resetPassword(i){return e.__awaiter(this,void 0,void 0,(function*(){const e=JSON.stringify({mail:i}),t={method:"post",url:`${this.config.url}/user/password?_format=json`,headers:{"content-type":"application/json"},data:e};try{yield a.default(t).catch(c)}catch(e){if("The user has not been activated or is blocked."===e.message)return void(yield this._sendVerificationEmail(i));c(e)}}))}delete(){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(!0),i={method:"delete",url:`${this.config.url}/user/${this.id}?_format=json`,headers:{Authorization:`Bearer ${e}`}};yield a.default(i).catch(c),this.logOut()}))}updateRemote(i){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(),t={method:"patch",url:`${this.config.url}/user/${this.id}?_format=json`,data:i,headers:{Authorization:`Bearer ${e}`},timeout:l};yield a.default(t),yield this._refreshAccessToken(),this.save()}))}refreshProfile(){return e.__awaiter(this,void 0,void 0,(function*(){return this._refreshingProfilePromise||(this._refreshingProfilePromise=Promise.resolve().then((()=>e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(!0);if(this.data.verified){const i={url:`${this.config.url}/user/${this.id}?_format=json`,headers:{Authorization:`Bearer ${e}`},timeout:l},{data:t}=yield a.default(i).catch(c),s=d(t);Object.assign(this.data,Object.assign({email:t.mail[0].value,profileFetched:!0},s))}yield this.save(),delete this._refreshingProfilePromise})))).catch((e=>{throw delete this._refreshingProfilePromise,e}))),this._refreshingProfilePromise}))}hasLogIn(){return console.warn("hasLogIn is deprecated, please use isLoggedIn instead."),this.isLoggedIn()}isLoggedIn(){return this.data.email,!!this.id}logOut(){return e.__awaiter(this,void 0,void 0,(function*(){return this.reset()}))}reset(e){return super.reset(Object.assign(Object.assign({},h),e))}getAccessToken(i){return e.__awaiter(this,void 0,void 0,(function*(){if(!i&&!this.isLoggedIn())throw new Error("User is not logged in.");const{access_token:e}=this.data.tokens||{},s=function(e){if(!e)return!0;const{exp:i}=t.jwtDecode(e),s=1e3*i;return Date.now()+12e4>s}(e);if(!e||s||i)try{yield this._refreshAccessToken()}catch(e){console.error(e);const i="The refresh token is invalid."===e.message,t="Token has no user email."===e.message;if(i||t)throw yield this.logOut(),new Error("User re-login is required.");throw e}return this.data.tokens.access_token}))}_sendVerificationEmail(i){return e.__awaiter(this,void 0,void 0,(function*(){const e=JSON.stringify({mail:[{value:i||this.data.email}]}),t={method:"post",url:`${this.config.url}/user/register-with-password?_format=json&resendVerificationEmail=true`,headers:{"content-type":"application/json"},data:e,timeout:l};return a.default(t).catch(c)}))}_exchangePasswordToTokens(i,t){return e.__awaiter(this,void 0,void 0,(function*(){var e;const s=new FormData;s.append("grant_type","password"),s.append("username",i),s.append("password",t),s.append("client_id",this.config.clientId),this.config.clientPass&&s.append("client_secret",this.config.clientPass),(null===(e=this.config.scopes)||void 0===e?void 0:e.length)&&s.append("scope",this.config.scopes.join(" "));const r={method:"post",url:`${this.config.url}/oauth/token`,data:s},{data:o}=yield a.default(r).catch(c);return o}))}_refreshAccessToken(){return e.__awaiter(this,void 0,void 0,(function*(){return this._refreshingTokenPromise||(this._refreshingTokenPromise=Promise.resolve().then((()=>e.__awaiter(this,void 0,void 0,(function*(){const{refresh_token:e}=this.data.tokens||{};if(!e)throw new Error("No user session refresh token was found");const i=new FormData;i.append("grant_type","refresh_token"),i.append("refresh_token",e),i.append("client_id",this.config.clientId),this.config.clientPass&&i.append("client_secret",this.config.clientPass);const s={method:"post",url:`${this.config.url}/oauth/token`,data:i,timeout:l},{data:r}=yield a.default(s).catch(c),o=Object.assign(Object.assign({},this.data.tokens),r),n=t.jwtDecode(o.access_token),{email:h}=n;if(!h)throw new Error("Token has no user email.");const{iss:u,email_verified:f}=n,g=n["http://indicia.org.uk/user:id"],m=n.scopes,v=d(n);this.id=n.sub,Object.assign(this.data,Object.assign({email:h,roles:m,verified:f,iss:u,indiciaUserId:g,tokens:o},v)),yield this.save(),delete this._refreshingTokenPromise})))).catch((e=>{throw delete this._refreshingTokenPromise,e}))),this._refreshingTokenPromise}))}}u.loginSchema=s.object({email:s.z.string().email("Please fill in"),password:s.z.string().min(1,"Please fill in")}),u.loginSchemaBackend=s.object({id:s.z.number(),email:s.z.string().email()}),u.resetSchema=s.object({email:s.z.string().email("Please fill in")}),u.registerSchema=s.object({email:s.z.string().email("Please fill in"),password:s.z.string().min(1,"Please fill in")}),u.registerSchemaBackend=s.object({uid:s.z.array(s.object({value:s.z.number()}))}),exports.default=u;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib");function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var a=t(require("axios"));exports.fetchElasticSample=function(t){return e.__awaiter(this,arguments,void 0,(function*({id:e,cid:t,url:i,accessToken:o}){var r,s,n;let d=JSON.stringify({size:1e3,query:{bool:{must:[{match:{id:e}}]}}});e||(d=JSON.stringify({size:1e3,query:{bool:{must:[{match:{"event.source_system_key":t}}]}}}));const u={Authorization:`Bearer ${o}`},l={method:"post",url:`${i}/index.php/services/rest/es-samples/_search`,headers:Object.assign({"Content-Type":"application/json"},u),data:d},c=((null===(n=null===(s=null===(r=(yield a.default.request(l)).data)||void 0===r?void 0:r.hits)||void 0===s?void 0:s.hits)||void 0===n?void 0:n.map((e=>e._source)))||[])[0];if(!c)throw new Error(`Remote sample with id ${e||t} was not found`);return c}))},exports.fetchElasticSubSamples=function(t){return e.__awaiter(this,arguments,void 0,(function*({parentId:e,url:t,accessToken:i}){var o,r,s;const n=JSON.stringify({size:2e3,query:{bool:{must:[{terms:{"event.parent_event_id":Array.isArray(e)?e:[e]}}]}},_source:["id","event.event_id","event.parent_event_id","event.source_system_key","event.attributes","event.media","event.event_remarks","event.date_start","metadata.created_on","metadata.updated_on","metadata.survey.id","metadata.group.id","metadata.trial","location.geom","location.output_sref_system","location.output_sref","location.point","location.code","location.name","location.verbatim_locality"]}),d={Authorization:`Bearer ${i}`},u={method:"post",url:`${t}/index.php/services/rest/es-samples/_search`,headers:Object.assign({"Content-Type":"application/json"},d),data:n};return(null===(s=null===(r=null===(o=(yield a.default.request(u)).data)||void 0===o?void 0:o.hits)||void 0===r?void 0:r.hits)||void 0===s?void 0:s.map((e=>e._source)))||[]}))};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib");function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var a=t(require("axios"));exports.fetchElasticSample=function(t){return e.__awaiter(this,arguments,void 0,(function*({id:e,cid:t,url:i,accessToken:o}){var r,s,n;let d=JSON.stringify({size:1e3,query:{bool:{must:[{match:{id:e}}]}}});e||(d=JSON.stringify({size:1e3,query:{bool:{must:[{match:{"event.source_system_key":t}}]}}}));const u={Authorization:`Bearer ${o}`},l={method:"post",url:`${i}/index.php/services/rest/es-samples/_search`,headers:Object.assign({"Content-Type":"application/json"},u),data:d},c=((null===(n=null===(s=null===(r=(yield a.default.request(l)).data)||void 0===r?void 0:r.hits)||void 0===s?void 0:s.hits)||void 0===n?void 0:n.map((e=>e._source)))||[])[0];if(!c)throw new Error(`Remote sample with id ${e||t} was not found`);return c}))},exports.fetchElasticSubSamples=function(t){return e.__awaiter(this,arguments,void 0,(function*({parentId:e,url:t,accessToken:i}){var o,r,s;const n=JSON.stringify({size:2e3,query:{bool:{must:[{terms:{"event.parent_event_id":Array.isArray(e)?e:[e]}}]}},_source:["id","event.event_id","event.parent_event_id","event.source_system_key","event.attributes","event.media","event.event_remarks","event.date_start","metadata.created_on","metadata.updated_on","metadata.survey.id","metadata.group.id","metadata.trial","location.geom","location.output_sref_system","location.output_sref","location.point","location.code","location.name","location.location_id","location.verbatim_locality"]}),d={Authorization:`Bearer ${i}`},u={method:"post",url:`${t}/index.php/services/rest/es-samples/_search`,headers:Object.assign({"Content-Type":"application/json"},d),data:n};return(null===(s=null===(r=null===(o=(yield a.default.request(u)).data)||void 0===o?void 0:o.hits)||void 0===r?void 0:r.hits)||void 0===s?void 0:s.map((e=>e._source)))||[]}))};
@@ -0,0 +1 @@
1
+ export {};
@@ -1,3 +1,4 @@
1
+ import Model from '../Model';
1
2
  export declare const getErrorMessageFromObject: (errors: any) => string;
2
3
  export interface RemoteConfig {
3
4
  id?: number | string;
@@ -37,4 +38,18 @@ export type ElasticSearchResponse<T> = {
37
38
  export declare const parseRemoteAttrs: (config: {
38
39
  [key: string]: AttrConfig;
39
40
  }, remoteAttrs: RemoteAttr[], isOccurrence?: boolean) => any;
41
+ export type CustomAttr = {
42
+ attribute_id: string;
43
+ value_id: string;
44
+ caption: string;
45
+ data_type: string;
46
+ multi_value: string;
47
+ value: string;
48
+ raw_value: string;
49
+ upper_value: any;
50
+ };
51
+ export declare function getLocalAttributes(doc: any, schema: any): {
52
+ [k: string]: any;
53
+ };
54
+ export declare const assignIfMissing: (model: Model, key: string, value: any) => void;
40
55
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flumens/models",
3
- "version": "0.24.0",
3
+ "version": "0.25.0",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "scripts": {