@memberjunction/graphql-dataprovider 2.3.1 → 2.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,12 +1,12 @@
1
- var K=Object.defineProperty;var N=(V,e)=>K(V,"name",{value:e,configurable:!0});import{gql as R,GraphQLClient as Q}from"graphql-request";import{gql as we}from"graphql-request";import{ProviderConfigDataBase as A,ProviderBase as O,LogError as D,UserInfo as M,ProviderType as q,BaseEntityResult as _,EntityFieldTSType as S,TransactionItem as B,UserRoleInfo as b,TransactionGroupBase as J,TransactionResult as j,BaseEntity as W,Metadata as z,RunView as H,RunReport as X,RunQuery as Y}from"@memberjunction/core";import{ViewInfo as k}from"@memberjunction/core-entities";import{openDB as Z}from"@tempfix/idb";import{Observable as ee}from"rxjs";import{createClient as te}from"graphql-ws";import{MJGlobal as ae,MJEventType as se}from"@memberjunction/global";const G=class G{constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const s in e)s in this._fieldMap&&(e[this._fieldMap[s]]=e[s],delete e[s]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([s,a])=>a===e)?.[0]??e}ReverseMapFields(e){const s=Object.fromEntries(Object.entries(this._fieldMap).map(([a,t])=>[t,a]));for(const a in e)a in s&&(e[s[a]]=e[a],delete e[a]);return e}};N(G,"FieldMapper");let h=G;const T=class T extends A{get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,s,a,t,r,l,i){super({Token:e,URL:s,WSURL:a,RefreshTokenFunction:t},r,l,i)}};N(T,"GraphQLProviderConfigData");let C=T;const d=class d extends O{constructor(){super(...arguments),this._innerCurrentUserQueryString=`CurrentUser {
1
+ var K=Object.defineProperty;var N=(V,e)=>K(V,"name",{value:e,configurable:!0});import{gql as R,GraphQLClient as Q}from"graphql-request";import{gql as we}from"graphql-request";import{ProviderConfigDataBase as A,ProviderBase as O,LogError as D,UserInfo as _,ProviderType as q,BaseEntityResult as M,EntityFieldTSType as S,TransactionItem as B,UserRoleInfo as b,TransactionGroupBase as J,TransactionResult as j,BaseEntity as W,Metadata as z,RunView as H,RunReport as X,RunQuery as Y}from"@memberjunction/core";import{ViewInfo as k}from"@memberjunction/core-entities";import{openDB as Z}from"@tempfix/idb";import{Observable as ee}from"rxjs";import{createClient as te}from"graphql-ws";import{MJGlobal as ae,MJEventType as se}from"@memberjunction/global";const G=class G{constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const s in e)s in this._fieldMap&&(e[this._fieldMap[s]]=e[s],delete e[s]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([s,a])=>a===e)?.[0]??e}ReverseMapFields(e){const s=Object.fromEntries(Object.entries(this._fieldMap).map(([a,t])=>[t,a]));for(const a in e)a in s&&(e[s[a]]=e[a],delete e[a]);return e}};N(G,"FieldMapper");let h=G;const T=class T extends A{get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,s,a,t,r,l,i){super({Token:e,URL:s,WSURL:a,RefreshTokenFunction:t},r,l,i)}};N(T,"GraphQLProviderConfigData");let C=T;const d=class d extends O{constructor(){super(...arguments),this._innerCurrentUserQueryString=`CurrentUser {
2
2
  ${this.userInfoString()}
3
- UserRolesArray {
3
+ UserRoles_UserIDArray {
4
4
  ${this.userRoleInfoString()}
5
5
  }
6
6
  }
7
7
  `,this._currentUserQuery=R`query CurrentUserAndRoles {
8
8
  ${this._innerCurrentUserQueryString}
9
- }`,this._wsClient=null,this._pushStatusRequests=[]}get ConfigData(){return d._configData}GenerateUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var s=Math.random()*16|0,a=e==="x"?s:s&3|8;return a.toString(16)})}async Config(e){try{return d._sessionId===void 0&&(d._sessionId=this.GenerateUUID()),d._configData=e,d._client||(d._client=d.CreateNewGraphQLClient(e.URL,e.Token,d._sessionId)),super.Config(e)}catch(s){throw D(s),s}}get sessionId(){return d._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await d.ExecuteGQL(this._currentUserQuery,null);if(e){const s=this.ConvertBackToMJFields(e.CurrentUser),a=s.UserRolesArray.map(t=>this.ConvertBackToMJFields(t));return s.UserRolesArray=a,new M(this,{...s,UserRoles:a})}}async RunReport(e,s){const a=R`
9
+ }`,this._wsClient=null,this._pushStatusRequests=[]}get ConfigData(){return d._configData}GenerateUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var s=Math.random()*16|0,a=e==="x"?s:s&3|8;return a.toString(16)})}async Config(e){try{return d._sessionId===void 0&&(d._sessionId=this.GenerateUUID()),d._configData=e,d._client||(d._client=d.CreateNewGraphQLClient(e.URL,e.Token,d._sessionId)),super.Config(e)}catch(s){throw D(s),s}}get sessionId(){return d._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await d.ExecuteGQL(this._currentUserQuery,null);if(e){const s=this.ConvertBackToMJFields(e.CurrentUser),a=s.UserRoles_UserIDArray.map(t=>this.ConvertBackToMJFields(t));return s.UserRoles_UserIDArray=a,new _(this,{...s,UserRoles:a})}}async RunReport(e,s){const a=R`
10
10
  query GetReportDataQuery ($ReportID: String!) {
11
11
  GetReportData(ReportID: $ReportID) {
12
12
  Success
@@ -104,7 +104,7 @@ var K=Object.defineProperty;var N=(V,e)=>K(V,"name",{value:e,configurable:!0});i
104
104
  Message
105
105
  }
106
106
  }
107
- }`,t={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(l=>({FieldName:l.FieldName,Value:l.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(l=>l.Copy())};return(await d.ExecuteGQL(a,{request:t}))?.MergeRecords}catch(a){return D(a),{Success:!1,OverallStatus:a&&a.message?a.message:a,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,s,a){const t=new _;try{e.RegisterTransactionPreprocessing();const r={input:{}},l=e.IsSaved?"Update":"Create";t.StartedAt=new Date,t.Type=e.IsSaved?"update":"create",t.OriginalValues=e.Fields.map(u=>({FieldName:u.CodeName,Value:u.Value})),e.ResultHistory.push(t);const i=`${l}${e.EntityInfo.ClassName}`,n=e.Fields.filter(u=>!u.ReadOnly||u.IsPrimaryKey&&e.IsSaved),p=new h,f=` ${i}(input: $input) {
107
+ }`,t={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(l=>({FieldName:l.FieldName,Value:l.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(l=>l.Copy())};return(await d.ExecuteGQL(a,{request:t}))?.MergeRecords}catch(a){return D(a),{Success:!1,OverallStatus:a&&a.message?a.message:a,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,s,a){const t=new M;try{e.RegisterTransactionPreprocessing();const r={input:{}},l=e.IsSaved?"Update":"Create";t.StartedAt=new Date,t.Type=e.IsSaved?"update":"create",t.OriginalValues=e.Fields.map(u=>({FieldName:u.CodeName,Value:u.Value})),e.ResultHistory.push(t);const i=`${l}${e.EntityInfo.ClassName}`,n=e.Fields.filter(u=>!u.ReadOnly||u.IsPrimaryKey&&e.IsSaved),p=new h,f=` ${i}(input: $input) {
108
108
  ${e.Fields.map(u=>p.MapFieldName(u.CodeName)).join(`
109
109
  `)}
110
110
  }`,y=R`mutation ${l}${e.EntityInfo.ClassName} ($input: ${i}Input!) {
@@ -122,7 +122,7 @@ var K=Object.defineProperty;var N=(V,e)=>K(V,"name",{value:e,configurable:!0});i
122
122
  ${l.Fields.map(n=>n.CodeName).join(`
123
123
  `)}
124
124
  }
125
- `}return a}async Delete(e,s,a){const t=new _;try{e.RegisterTransactionPreprocessing(),t.StartedAt=new Date,t.Type="delete",t.OriginalValues=e.Fields.map(o=>({FieldName:o.CodeName,Value:o.Value})),e.ResultHistory.push(t);const r={},l=[];let i="",n="",p="";for(let o of e.PrimaryKey.KeyValuePairs){const c=e.Fields.find(m=>m.Name.trim().toLowerCase()===o.FieldName.trim().toLowerCase());r[c.CodeName]=c.Value,l.push({varName:c.CodeName,inputType:c.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${c.CodeName}: $${c.CodeName}`,n.length>0&&(n+=", "),n+=`$${c.CodeName}: ${c.EntityFieldInfo.GraphQLType}!`,p.length>0&&(p+=`
125
+ `}return a}async Delete(e,s,a){const t=new M;try{e.RegisterTransactionPreprocessing(),t.StartedAt=new Date,t.Type="delete",t.OriginalValues=e.Fields.map(o=>({FieldName:o.CodeName,Value:o.Value})),e.ResultHistory.push(t);const r={},l=[];let i="",n="",p="";for(let o of e.PrimaryKey.KeyValuePairs){const c=e.Fields.find(m=>m.Name.trim().toLowerCase()===o.FieldName.trim().toLowerCase());r[c.CodeName]=c.Value,l.push({varName:c.CodeName,inputType:c.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${c.CodeName}: $${c.CodeName}`,n.length>0&&(n+=", "),n+=`$${c.CodeName}: ${c.EntityFieldInfo.GraphQLType}!`,p.length>0&&(p+=`
126
126
  `),p+=`${c.CodeName}`}l.push({varName:"options___",inputType:"DeleteOptionsInput!"}),r.options___=s||{SkipEntityAIActions:!1,SkipEntityActions:!1};const f="Delete"+e.EntityInfo.ClassName,y=R`${f}(${i}, options___: $options___) {
127
127
  ${p}
128
128
  }
@@ -175,7 +175,7 @@ var K=Object.defineProperty;var N=(V,e)=>K(V,"name",{value:e,configurable:!0});i
175
175
  EntityName
176
176
  RecordName
177
177
  }
178
- }`,a=await d.ExecuteGQL(s,{info:e.map(t=>({EntityName:t.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.CompositeKey.KeyValuePairs)}}))});if(a&&a.GetEntityRecordNames)return a.GetEntityRecordNames}static async ExecuteGQL(e,s,a=!0){try{return await d._client.request(e,s)}catch(t){if(t&&t.response&&t.response.errors?.length>0)if(t.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(a)return await d.RefreshToken(),await d.ExecuteGQL(e,s,!1);throw D("JWT_EXPIRED and refreshTokenIfNeeded is false"),t}else throw t;else throw D(t),t}}static async RefreshToken(){if(d._configData.Data.RefreshTokenFunction){const e=await d._configData.Data.RefreshTokenFunction();if(e)d._configData.Token=e,d._client=this.CreateNewGraphQLClient(d._configData.URL,d._configData.Token,d._sessionId);else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static CreateNewGraphQLClient(e,s,a){return new Q(e,{headers:{authorization:"Bearer "+s,"x-session-id":a}})}userInfoString(){return this.infoString(new M(null,null))}userRoleInfoString(){return this.infoString(new b(null))}infoString(e){let s="";const a=Object.keys(e);for(const t of a)t.startsWith("__mj_")?s+=t.replace("__mj_","_mj__")+`
178
+ }`,a=await d.ExecuteGQL(s,{info:e.map(t=>({EntityName:t.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.CompositeKey.KeyValuePairs)}}))});if(a&&a.GetEntityRecordNames)return a.GetEntityRecordNames}static async ExecuteGQL(e,s,a=!0){try{return await d._client.request(e,s)}catch(t){if(t&&t.response&&t.response.errors?.length>0)if(t.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(a)return await d.RefreshToken(),await d.ExecuteGQL(e,s,!1);throw D("JWT_EXPIRED and refreshTokenIfNeeded is false"),t}else throw t;else throw D(t),t}}static async RefreshToken(){if(d._configData.Data.RefreshTokenFunction){const e=await d._configData.Data.RefreshTokenFunction();if(e)d._configData.Token=e,d._client=this.CreateNewGraphQLClient(d._configData.URL,d._configData.Token,d._sessionId);else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static CreateNewGraphQLClient(e,s,a){return new Q(e,{headers:{authorization:"Bearer "+s,"x-session-id":a}})}userInfoString(){return this.infoString(new _(null,null))}userRoleInfoString(){return this.infoString(new b(null))}infoString(e){let s="";const a=Object.keys(e);for(const t of a)t.startsWith("__mj_")?s+=t.replace("__mj_","_mj__")+`
179
179
  `:t.startsWith("_")||(s+=t+`
180
180
  `);return s}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new $),this._localStorageProvider}get Metadata(){return this}PushStatusUpdates(e=null){e||(e=this.sessionId),this._wsClient||(this._wsClient=te({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}}));const s=this._pushStatusRequests.find(r=>r.sessionId===e);if(s)return s.observable;const a=R`subscription StatusUpdates($sessionId: String!) {
181
181
  statusUpdates(sessionId: $sessionId) {