@memberjunction/graphql-dataprovider 2.27.1 → 2.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -105,6 +105,10 @@ declare class GraphQLDataProvider extends ProviderBase implements IEntityDataPro
105
105
  /**************************************************************************/
106
106
  /**************************************************************************/
107
107
  RunQuery(params: RunQueryParams, contextUser?: UserInfo): Promise<RunQueryResult>;
108
+ RunQueryByID(QueryID: string, contextUser?: UserInfo): Promise<RunQueryResult>;
109
+ RunQueryByName(QueryName: string, contextUser?: UserInfo): Promise<RunQueryResult>;
110
+ protected get QueryReturnFieldList(): string;
111
+ protected TransformQueryPayload(data: any): RunQueryResult;
108
112
  /**************************************************************************/
109
113
  /**************************************************************************/
110
114
  /**************************************************************************/
package/dist/index.d.mts CHANGED
@@ -105,6 +105,10 @@ declare class GraphQLDataProvider extends ProviderBase implements IEntityDataPro
105
105
  /**************************************************************************/
106
106
  /**************************************************************************/
107
107
  RunQuery(params: RunQueryParams, contextUser?: UserInfo): Promise<RunQueryResult>;
108
+ RunQueryByID(QueryID: string, contextUser?: UserInfo): Promise<RunQueryResult>;
109
+ RunQueryByName(QueryName: string, contextUser?: UserInfo): Promise<RunQueryResult>;
110
+ protected get QueryReturnFieldList(): string;
111
+ protected TransformQueryPayload(data: any): RunQueryResult;
108
112
  /**************************************************************************/
109
113
  /**************************************************************************/
110
114
  /**************************************************************************/
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var ye=Object.defineProperty;var f=(E,e)=>ye(E,"name",{value:e,configurable:!0});import{gql as h,GraphQLClient as ie}from"graphql-request";import{gql as Qe}from"graphql-request";import{TransactionGroupBase as me,TransactionResult as pe,ProviderConfigDataBase as fe,ProviderBase as he,LogError as w,UserInfo as ne,ProviderType as De,BaseEntityResult as oe,EntityFieldTSType as N,TransactionItem as ue,UserRoleInfo as we,SetProvider as Re}from"@memberjunction/core";import{ViewInfo as le}from"@memberjunction/core-entities";import{openDB as Ee}from"@tempfix/idb";import{Observable as Ne}from"rxjs";import{createClient as ge}from"graphql-ws";import{v4 as Se}from"uuid";import{SafeJSONParse as ce,MJGlobal as Ie,MJEventType as Ve}from"@memberjunction/global";const B=class B{constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const a in e)a in this._fieldMap&&(e[this._fieldMap[a]]=e[a],delete e[a]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([a,s])=>s===e)?.[0]??e}ReverseMapFields(e){const a=Object.fromEntries(Object.entries(this._fieldMap).map(([s,t])=>[t,s]));for(const s in e)s in a&&(e[a[s]]=e[s],delete e[s]);return e}};f(B,"FieldMapper");let I=B;const O=class O extends me{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=h`
1
+ var ye=Object.defineProperty;var h=(R,e)=>ye(R,"name",{value:e,configurable:!0});import{gql as p,GraphQLClient as ie}from"graphql-request";import{gql as Be}from"graphql-request";import{TransactionGroupBase as me,TransactionResult as fe,ProviderConfigDataBase as pe,ProviderBase as he,LogError as w,UserInfo as ne,ProviderType as De,BaseEntityResult as oe,EntityFieldTSType as E,TransactionItem as ue,UserRoleInfo as we,SetProvider as Ne}from"@memberjunction/core";import{ViewInfo as le}from"@memberjunction/core-entities";import{openDB as Re}from"@tempfix/idb";import{Observable as Ee}from"rxjs";import{createClient as ge}from"graphql-ws";import{v4 as Se}from"uuid";import{SafeJSONParse as ce,MJGlobal as Ie,MJEventType as Ve}from"@memberjunction/global";const k=class k{constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const a in e)a in this._fieldMap&&(e[this._fieldMap[a]]=e[a],delete e[a]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([a,s])=>s===e)?.[0]??e}ReverseMapFields(e){const a=Object.fromEntries(Object.entries(this._fieldMap).map(([s,t])=>[t,s]));for(const s in e)s in a&&(e[a[s]]=e[s],delete e[s]);return e}};h(k,"FieldMapper");let I=k;const O=class O extends me{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=p`
2
2
  mutation ExecuteTransactionGroup($group: TransactionInputType!) {
3
3
  ExecuteTransactionGroup(group: $group) {
4
4
  Success
@@ -6,15 +6,15 @@ var ye=Object.defineProperty;var f=(E,e)=>ye(E,"name",{value:e,configurable:!0})
6
6
  ResultsJSON
7
7
  }
8
8
  }
9
- `,a=[];for(const r of this.PendingTransactions)a.push({EntityName:r.BaseEntity.EntityInfo.Name,EntityObjectJSON:await r.BaseEntity.GetDataObjectJSON(),OperationType:r.OperationType});const s={group:{Items:a,Variables:this.Variables.map(r=>({Name:r.Name,ItemIndex:this.MapVariableEntityObjectToPosition(r),FieldName:r.FieldName,Type:r.Type}))}},t=await this._provider.ExecuteGQL(e,s);if(t&&t.ExecuteTransactionGroup){const r=t.ExecuteTransactionGroup,u=[];for(let n=0;n<this.PendingTransactions.length;n++){const i=r.ResultsJSON[n],m=ce(i),p=this.PendingTransactions[n];u.push(new pe(p,m,m!==null))}return u}else throw new Error("Failed to execute transaction group")}};f(O,"GraphQLTransactionGroup");let V=O;const q=class q extends fe{get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,a,s,t,r,u,n,i){super({Token:e,URL:a,WSURL:s,MJAPIKey:i,RefreshTokenFunction:t},r,u,n)}};f(q,"GraphQLProviderConfigData");let F=q;const R=class R extends he{constructor(){super(),this._innerCurrentUserQueryString=`CurrentUser {
9
+ `,a=[];for(const r of this.PendingTransactions)a.push({EntityName:r.BaseEntity.EntityInfo.Name,EntityObjectJSON:await r.BaseEntity.GetDataObjectJSON(),OperationType:r.OperationType});const s={group:{Items:a,Variables:this.Variables.map(r=>({Name:r.Name,ItemIndex:this.MapVariableEntityObjectToPosition(r),FieldName:r.FieldName,Type:r.Type}))}},t=await this._provider.ExecuteGQL(e,s);if(t&&t.ExecuteTransactionGroup){const r=t.ExecuteTransactionGroup,u=[];for(let n=0;n<this.PendingTransactions.length;n++){const i=r.ResultsJSON[n],m=ce(i),f=this.PendingTransactions[n];u.push(new fe(f,m,m!==null))}return u}else throw new Error("Failed to execute transaction group")}};h(O,"GraphQLTransactionGroup");let V=O;const q=class q extends pe{get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,a,s,t,r,u,n,i){super({Token:e,URL:a,WSURL:s,MJAPIKey:i,RefreshTokenFunction:t},r,u,n)}};h(q,"GraphQLProviderConfigData");let F=q;const N=class N extends he{constructor(){super(),this._innerCurrentUserQueryString=`CurrentUser {
10
10
  ${this.userInfoString()}
11
11
  UserRoles_UserIDArray {
12
12
  ${this.userRoleInfoString()}
13
13
  }
14
14
  }
15
- `,this._currentUserQuery=h`query CurrentUserAndRoles {
15
+ `,this._currentUserQuery=p`query CurrentUserAndRoles {
16
16
  ${this._innerCurrentUserQueryString}
17
- }`,this._wsClient=null,this._pushStatusRequests=[],R._instance||(R._instance=this)}static get Instance(){return R._instance}get ConfigData(){return this._configData}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return Se()}get LocalStoragePrefix(){return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async Config(e,a){try{const s=this.GenerateUUID();return a?(this._sessionId=s,this._configData=e,this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey)):(R.Instance._sessionId===void 0&&(R.Instance._sessionId=s),R.Instance._configData=e,R.Instance._client||(R.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,R.Instance._sessionId,e.MJAPIKey))),super.Config(e)}catch(s){throw w(s),s}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const a=this.ConvertBackToMJFields(e.CurrentUser),s=a.UserRoles_UserIDArray.map(t=>this.ConvertBackToMJFields(t));return a.UserRoles_UserIDArray=s,new ne(this,{...a,UserRoles:s})}}async RunReport(e,a){const s=h`
17
+ }`,this._wsClient=null,this._pushStatusRequests=[],N._instance||(N._instance=this)}static get Instance(){return N._instance}get ConfigData(){return this._configData}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return Se()}get LocalStoragePrefix(){return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async Config(e,a){try{const s=this.GenerateUUID();return a?(this._sessionId=s,this._configData=e,this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey)):(N.Instance._sessionId===void 0&&(N.Instance._sessionId=s),N.Instance._configData=e,N.Instance._client||(N.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,N.Instance._sessionId,e.MJAPIKey))),super.Config(e)}catch(s){throw w(s),s}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const a=this.ConvertBackToMJFields(e.CurrentUser),s=a.UserRoles_UserIDArray.map(t=>this.ConvertBackToMJFields(t));return a.UserRoles_UserIDArray=s,new ne(this,{...a,UserRoles:s})}}async RunReport(e,a){const s=p`
18
18
  query GetReportDataQuery ($ReportID: String!) {
19
19
  GetReportData(ReportID: $ReportID) {
20
20
  Success
@@ -23,20 +23,28 @@ var ye=Object.defineProperty;var f=(E,e)=>ye(E,"name",{value:e,configurable:!0})
23
23
  ExecutionTime
24
24
  ErrorMessage
25
25
  }
26
- }`,t=await this.ExecuteGQL(s,{ReportID:e.ReportID});if(t&&t.GetReportData)return{ReportID:e.ReportID,Success:t.GetReportData.Success,Results:JSON.parse(t.GetReportData.Results),RowCount:t.GetReportData.RowCount,ExecutionTime:t.GetReportData.ExecutionTime,ErrorMessage:t.GetReportData.ErrorMessage}}async RunQuery(e,a){const s=h`
26
+ }`,t=await this.ExecuteGQL(s,{ReportID:e.ReportID});if(t&&t.GetReportData)return{ReportID:e.ReportID,Success:t.GetReportData.Success,Results:JSON.parse(t.GetReportData.Results),RowCount:t.GetReportData.RowCount,ExecutionTime:t.GetReportData.ExecutionTime,ErrorMessage:t.GetReportData.ErrorMessage}}async RunQuery(e,a){if(e.QueryID)return this.RunQueryByID(e.QueryID,a);if(e.QueryName)return this.RunQueryByName(e.QueryName,a);throw new Error("No QueryID or QueryName provided to RunQuery")}async RunQueryByID(e,a){const s=p`
27
27
  query GetQueryDataQuery ($QueryID: String!) {
28
28
  GetQueryData(QueryID: $QueryID) {
29
+ ${this.QueryReturnFieldList}
30
+ }
31
+ }`,t=await this.ExecuteGQL(s,{QueryID:e});if(t&&t.GetQueryData)return this.TransformQueryPayload(t.GetQueryData)}async RunQueryByName(e,a){const s=p`
32
+ query GetQueryDataByNameQuery ($QueryName: String!) {
33
+ GetQueryDataByName(QueryName: $QueryName) {
34
+ ${this.QueryReturnFieldList}
35
+ }
36
+ }`,t=await this.ExecuteGQL(s,{QueryName:e});if(t&&t.GetQueryDataByName)return this.TransformQueryPayload(t.GetQueryDataByName)}get QueryReturnFieldList(){return`
29
37
  Success
38
+ QueryID
39
+ QueryName
30
40
  Results
31
41
  RowCount
32
42
  ExecutionTime
33
- ErrorMessage
34
- }
35
- }`,t=await this.ExecuteGQL(s,{QueryID:e.QueryID});if(t&&t.GetQueryData)return{QueryID:e.QueryID,Success:t.GetQueryData.Success,Results:JSON.parse(t.GetQueryData.Results),RowCount:t.GetQueryData.RowCount,ExecutionTime:t.GetQueryData.ExecutionTime,ErrorMessage:t.GetQueryData.ErrorMessage}}async RunView(e,a){try{let s="",t="";if(e){const r={};let u,n;if(e.ViewEntity)n=e.ViewEntity,u=n.Entity;else{const{entityName:o,v:l}=await this.getEntityNameAndUserView(e,a);n=l,u=o}const i=this.Entities.find(o=>o.Name===u);if(!i)throw new Error(`Entity ${u} not found in metadata`);let m=!1;e.ViewID?(s=`Run${i.ClassName}ViewByID`,t="RunViewByIDInput",r.ViewID=e.ViewID):e.ViewName?(s=`Run${i.ClassName}ViewByName`,t="RunViewByNameInput",r.ViewName=e.ViewName):(m=!0,s=`Run${i.ClassName}DynamicView`,t="RunDynamicViewInput",r.EntityName=e.EntityName),r.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",r.OrderBy=e.OrderBy?e.OrderBy:"",r.UserSearchString=e.UserSearchString?e.UserSearchString:"",r.Fields=e.Fields,r.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,r.MaxRows=e.MaxRows?e.MaxRows:0,r.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,r.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(r.AuditLogDescription=e.AuditLogDescription),m||(r.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",r.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,r.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",r.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1);const p=this.getViewRunTimeFieldList(i,n,e,m),d=h`
43
+ ErrorMessage`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage}}catch(a){return w(`Error transforming query payload: ${a}`),null}}async RunView(e,a){try{let s="",t="";if(e){const r={};let u,n;if(e.ViewEntity)n=e.ViewEntity,u=n.Entity;else{const{entityName:o,v:l}=await this.getEntityNameAndUserView(e,a);n=l,u=o}const i=this.Entities.find(o=>o.Name===u);if(!i)throw new Error(`Entity ${u} not found in metadata`);let m=!1;e.ViewID?(s=`Run${i.ClassName}ViewByID`,t="RunViewByIDInput",r.ViewID=e.ViewID):e.ViewName?(s=`Run${i.ClassName}ViewByName`,t="RunViewByNameInput",r.ViewName=e.ViewName):(m=!0,s=`Run${i.ClassName}DynamicView`,t="RunDynamicViewInput",r.EntityName=e.EntityName),r.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",r.OrderBy=e.OrderBy?e.OrderBy:"",r.UserSearchString=e.UserSearchString?e.UserSearchString:"",r.Fields=e.Fields,r.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,r.MaxRows=e.MaxRows?e.MaxRows:0,r.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,r.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(r.AuditLogDescription=e.AuditLogDescription),m||(r.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",r.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,r.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",r.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1);const f=this.getViewRunTimeFieldList(i,n,e,m),d=p`
36
44
  query RunViewQuery ($input: ${t}!) {
37
45
  ${s}(input: $input) {
38
46
  Results {
39
- ${p.join(`
47
+ ${f.join(`
40
48
  `)}
41
49
  }
42
50
  UserViewRunID
@@ -46,7 +54,7 @@ var ye=Object.defineProperty;var f=(E,e)=>ye(E,"name",{value:e,configurable:!0})
46
54
  Success
47
55
  ErrorMessage
48
56
  }
49
- }`,c=await this.ExecuteGQL(d,{input:r});if(c&&c[s]){const o=c[s].Results;if(o&&o.length>0){const l=i.Fields.filter(y=>y.CodeName!==y.Name&&y.CodeName!==void 0);o.forEach(y=>{this.ConvertBackToMJFields(y),l.forEach(D=>{y[D.Name]=y[D.CodeName]})})}return c[s]}}else throw"No parameters passed to RunView";return null}catch(s){throw w(s),s}}async RunViews(e,a){try{let s=[],t=[],r=[];for(const i of e){let m="",p="";const d={};let c=null,o=null;if(i.ViewEntity)o=i.ViewEntity,c=o.Get("Entity");else{const{entityName:D,v:S}=await this.getEntityNameAndUserView(i,a);o=S,c=D}const l=this.Entities.find(D=>D.Name===c);if(!l)throw new Error(`Entity ${c} not found in metadata`);t.push(l);let y=!1;i.ViewID?(m=`Run${l.ClassName}ViewByID`,p="RunViewByIDInput",d.ViewID=i.ViewID):i.ViewName?(m=`Run${l.ClassName}ViewByName`,p="RunViewByNameInput",d.ViewName=i.ViewName):(y=!0,m=`Run${l.ClassName}DynamicView`,p="RunDynamicViewInput",d.EntityName=i.EntityName),d.ExtraFilter=i.ExtraFilter||"",d.OrderBy=i.OrderBy||"",d.UserSearchString=i.UserSearchString||"",d.Fields=i.Fields,d.IgnoreMaxRows=i.IgnoreMaxRows||!1,d.MaxRows=i.MaxRows||0,d.ForceAuditLog=i.ForceAuditLog||!1,d.ResultType=i.ResultType||"simple",i.AuditLogDescription&&i.AuditLogDescription.length>0&&(d.AuditLogDescription=i.AuditLogDescription),y||(d.ExcludeUserViewRunID=i.ExcludeUserViewRunID||"",d.ExcludeDataFromAllPriorViewRuns=i.ExcludeDataFromAllPriorViewRuns||!1,d.OverrideExcludeFilter=i.OverrideExcludeFilter||"",d.SaveViewResults=i.SaveViewResults||!1),s.push(d),r.push(...this.getViewRunTimeFieldList(l,o,i,y))}const u=h`
57
+ }`,c=await this.ExecuteGQL(d,{input:r});if(c&&c[s]){const o=c[s].Results;if(o&&o.length>0){const l=i.Fields.filter(y=>y.CodeName!==y.Name&&y.CodeName!==void 0);o.forEach(y=>{this.ConvertBackToMJFields(y),l.forEach(D=>{y[D.Name]=y[D.CodeName]})})}return c[s]}}else throw"No parameters passed to RunView";return null}catch(s){throw w(s),s}}async RunViews(e,a){try{let s=[],t=[],r=[];for(const i of e){let m="",f="";const d={};let c=null,o=null;if(i.ViewEntity)o=i.ViewEntity,c=o.Get("Entity");else{const{entityName:D,v:S}=await this.getEntityNameAndUserView(i,a);o=S,c=D}const l=this.Entities.find(D=>D.Name===c);if(!l)throw new Error(`Entity ${c} not found in metadata`);t.push(l);let y=!1;i.ViewID?(m=`Run${l.ClassName}ViewByID`,f="RunViewByIDInput",d.ViewID=i.ViewID):i.ViewName?(m=`Run${l.ClassName}ViewByName`,f="RunViewByNameInput",d.ViewName=i.ViewName):(y=!0,m=`Run${l.ClassName}DynamicView`,f="RunDynamicViewInput",d.EntityName=i.EntityName),d.ExtraFilter=i.ExtraFilter||"",d.OrderBy=i.OrderBy||"",d.UserSearchString=i.UserSearchString||"",d.Fields=i.Fields,d.IgnoreMaxRows=i.IgnoreMaxRows||!1,d.MaxRows=i.MaxRows||0,d.ForceAuditLog=i.ForceAuditLog||!1,d.ResultType=i.ResultType||"simple",i.AuditLogDescription&&i.AuditLogDescription.length>0&&(d.AuditLogDescription=i.AuditLogDescription),y||(d.ExcludeUserViewRunID=i.ExcludeUserViewRunID||"",d.ExcludeDataFromAllPriorViewRuns=i.ExcludeDataFromAllPriorViewRuns||!1,d.OverrideExcludeFilter=i.OverrideExcludeFilter||"",d.SaveViewResults=i.SaveViewResults||!1),s.push(d),r.push(...this.getViewRunTimeFieldList(l,o,i,y))}const u=p`
50
58
  query RunViewsQuery ($input: [RunViewGenericInput!]!) {
51
59
  RunViews(input: $input) {
52
60
  Results {
@@ -61,7 +69,7 @@ var ye=Object.defineProperty;var f=(E,e)=>ye(E,"name",{value:e,configurable:!0})
61
69
  Success
62
70
  ErrorMessage
63
71
  }
64
- }`,n=await this.ExecuteGQL(u,{input:s});if(n&&n.RunViews){const i=n.RunViews;for(const[m,p]of i.entries())p.Results=p.Results.map(d=>{let c=JSON.parse(d.Data);return this.ConvertBackToMJFields(c),c});return i}return null}catch(s){throw w(s),s}}async getEntityNameAndUserView(e,a){let s,t;if(e.EntityName)s=e.EntityName;else if(e.ViewID)t=await le.GetViewEntity(e.ViewID,a),s=t.Entity;else if(e.ViewName)t=await le.GetViewEntityByName(e.ViewName,a),s=t.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:s,v:t}}getViewRunTimeFieldList(e,a,s,t){const r=[],u=new I;if(s.Fields){for(const n of e.PrimaryKeys)s.Fields.find(i=>i.trim().toLowerCase()===n.Name.toLowerCase())===void 0&&r.push(n.Name);s.Fields.forEach(n=>{r.push(u.MapFieldName(n))})}else if(t)e.Fields.forEach(n=>{n.IsBinaryFieldType||r.push(u.MapFieldName(n.CodeName))});else{for(const n of e.PrimaryKeys)r.find(i=>i.trim().toLowerCase()===n.Name.toLowerCase())===void 0&&r.push(n.Name);a.Columns.forEach(n=>{n.hidden===!1&&!r.find(i=>i.trim().toLowerCase()===n.EntityField?.Name.trim().toLowerCase())&&n.EntityField&&r.push(u.MapFieldName(n.EntityField.CodeName))})}return r}get ProviderType(){return De.Network}async GetRecordChanges(e,a){try{const s={EntityName:"Record Changes",ExtraFilter:`RecordID = '${a.Values()}' AND Entity = '${e}'`},t=await this.RunView(s);return t?t.Results.sort((r,u)=>r.ChangedAt>u.ChangedAt?-1:1):null}catch(s){throw w(s),s}}async GetRecordDependencies(e,a){try{const s=h`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
72
+ }`,n=await this.ExecuteGQL(u,{input:s});if(n&&n.RunViews){const i=n.RunViews;for(const[m,f]of i.entries())f.Results=f.Results.map(d=>{let c=JSON.parse(d.Data);return this.ConvertBackToMJFields(c),c});return i}return null}catch(s){throw w(s),s}}async getEntityNameAndUserView(e,a){let s,t;if(e.EntityName)s=e.EntityName;else if(e.ViewID)t=await le.GetViewEntity(e.ViewID,a),s=t.Entity;else if(e.ViewName)t=await le.GetViewEntityByName(e.ViewName,a),s=t.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:s,v:t}}getViewRunTimeFieldList(e,a,s,t){const r=[],u=new I;if(s.Fields){for(const n of e.PrimaryKeys)s.Fields.find(i=>i.trim().toLowerCase()===n.Name.toLowerCase())===void 0&&r.push(n.Name);s.Fields.forEach(n=>{r.push(u.MapFieldName(n))})}else if(t)e.Fields.forEach(n=>{n.IsBinaryFieldType||r.push(u.MapFieldName(n.CodeName))});else{for(const n of e.PrimaryKeys)r.find(i=>i.trim().toLowerCase()===n.Name.toLowerCase())===void 0&&r.push(n.Name);a.Columns.forEach(n=>{n.hidden===!1&&!r.find(i=>i.trim().toLowerCase()===n.EntityField?.Name.trim().toLowerCase())&&n.EntityField&&r.push(u.MapFieldName(n.EntityField.CodeName))})}return r}get ProviderType(){return De.Network}async GetRecordChanges(e,a){try{const s={EntityName:"Record Changes",ExtraFilter:`RecordID = '${a.Values()}' AND Entity = '${e}'`},t=await this.RunView(s);return t?t.Results.sort((r,u)=>r.ChangedAt>u.ChangedAt?-1:1):null}catch(s){throw w(s),s}}async GetRecordDependencies(e,a){try{const s=p`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
65
73
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
66
74
  EntityName
67
75
  RelatedEntityName
@@ -73,7 +81,7 @@ var ye=Object.defineProperty;var f=(E,e)=>ye(E,"name",{value:e,configurable:!0})
73
81
  }
74
82
  }
75
83
  }
76
- }`,t={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(a.KeyValuePairs)}};return(await this.ExecuteGQL(s,t))?.GetRecordDependencies}catch(s){throw w(s),s}}ensureKeyValuePairValueIsString(e){return e.map(a=>({FieldName:a.FieldName,Value:a.Value.toString()}))}async GetRecordDuplicates(e,a){if(!e)return null;const s=h`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
84
+ }`,t={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(a.KeyValuePairs)}};return(await this.ExecuteGQL(s,t))?.GetRecordDependencies}catch(s){throw w(s),s}}ensureKeyValuePairValueIsString(e){return e.map(a=>({FieldName:a.FieldName,Value:a.Value.toString()}))}async GetRecordDuplicates(e,a){if(!e)return null;const s=p`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
77
85
  GetRecordDuplicates(params: $params) {
78
86
  Status
79
87
  ErrorMessage
@@ -95,7 +103,7 @@ var ye=Object.defineProperty;var f=(E,e)=>ye(E,"name",{value:e,configurable:!0})
95
103
  }
96
104
  }
97
105
  }
98
- }`;let t={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(u=>u.Copy())};const r=await this.ExecuteGQL(s,{params:t});if(r&&r.GetRecordDuplicates)return r.GetRecordDuplicates}async MergeRecords(e){const a=this.Entities.find(s=>s.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!a||!a.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const s=h`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
106
+ }`;let t={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(u=>u.Copy())};const r=await this.ExecuteGQL(s,{params:t});if(r&&r.GetRecordDuplicates)return r.GetRecordDuplicates}async MergeRecords(e){const a=this.Entities.find(s=>s.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!a||!a.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const s=p`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
99
107
  MergeRecords(request: $request) {
100
108
  Success
101
109
  OverallStatus
@@ -112,32 +120,32 @@ var ye=Object.defineProperty;var f=(E,e)=>ye(E,"name",{value:e,configurable:!0})
112
120
  Message
113
121
  }
114
122
  }
115
- }`,t={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(u=>({FieldName:u.FieldName,Value:u.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(u=>u.Copy())};return(await this.ExecuteGQL(s,{request:t}))?.MergeRecords}catch(s){return w(s),{Success:!1,OverallStatus:s&&s.message?s.message:s,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,a,s){const t=new oe;try{e.RegisterTransactionPreprocessing();const r={input:{}},u=e.IsSaved?"Update":"Create";t.StartedAt=new Date,t.Type=e.IsSaved?"update":"create",t.OriginalValues=e.Fields.map(c=>({FieldName:c.CodeName,Value:c.Value})),e.ResultHistory.push(t);const n=`${u}${e.EntityInfo.ClassName}`,i=e.Fields.filter(c=>!c.ReadOnly||c.IsPrimaryKey&&e.IsSaved),m=new I,p=` ${n}(input: $input) {
123
+ }`,t={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(u=>({FieldName:u.FieldName,Value:u.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(u=>u.Copy())};return(await this.ExecuteGQL(s,{request:t}))?.MergeRecords}catch(s){return w(s),{Success:!1,OverallStatus:s&&s.message?s.message:s,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,a,s){const t=new oe;try{e.RegisterTransactionPreprocessing();const r={input:{}},u=e.IsSaved?"Update":"Create";t.StartedAt=new Date,t.Type=e.IsSaved?"update":"create",t.OriginalValues=e.Fields.map(c=>({FieldName:c.CodeName,Value:c.Value})),e.ResultHistory.push(t);const n=`${u}${e.EntityInfo.ClassName}`,i=e.Fields.filter(c=>!c.ReadOnly||c.IsPrimaryKey&&e.IsSaved),m=new I,f=` ${n}(input: $input) {
116
124
  ${e.Fields.map(c=>m.MapFieldName(c.CodeName)).join(`
117
125
  `)}
118
- }`,d=h`mutation ${u}${e.EntityInfo.ClassName} ($input: ${n}Input!) {
119
- ${p}
126
+ }`,d=p`mutation ${u}${e.EntityInfo.ClassName} ($input: ${n}Input!) {
127
+ ${f}
120
128
  }
121
- `;for(let c=0;c<i.length;c++){const o=i[c];let l=o.Value;if(l)switch(o.EntityFieldInfo.TSType){case N.Date:l=l.getTime();break;case N.Boolean:typeof l!="boolean"&&(l=parseInt(l)!==0);break;case N.Number:if(typeof l!="number"){const y=Number(l);isNaN(y)||(l=y)}break}l===null&&o.EntityFieldInfo.AllowsNull===!1&&(o.EntityFieldInfo.DefaultValue!==null?l=o.EntityFieldInfo.DefaultValue:o.FieldType===N.Number||o.FieldType===N.Boolean?l=0:l=""),r.input[o.CodeName]=l}if(u.trim().toLowerCase()==="update"&&s.SkipOldValuesCheck===!1){const c=[];e.Fields.forEach(o=>{let l=null;o.OldValue!==null&&o.OldValue!==void 0&&(o.EntityFieldInfo.TSType===N.Date?l=o.OldValue.getTime().toString():o.EntityFieldInfo.TSType===N.Boolean?l=o.OldValue===!0?"1":"0":typeof o.OldValue!="string"?l=o.OldValue.toString():l=o.OldValue),c.push({Key:o.CodeName,Value:l})}),r.input.OldValues___=c}if(e.TransactionGroup){const c=[{varName:"input",inputType:n+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new ue(e,t.Type==="create"?"Create":"Update",p,r,{mutationName:n,mutationInputTypes:c},(o,l)=>{t.EndedAt=new Date,l&&o?(t.Success=!0,t.NewValues=this.ConvertBackToMJFields(o)):(t.Success=!1,t.Message="Transaction failed")})),!0}else{const c=await this.ExecuteGQL(d,r);if(c&&c[u+e.EntityInfo.ClassName])return t.Success=!0,t.EndedAt=new Date,t.NewValues=this.ConvertBackToMJFields(c[u+e.EntityInfo.ClassName]),t.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(r){return t.Success=!1,t.EndedAt=new Date,t.Message=r.response?.errors?.length>0?r.response.errors[0].message:r.message,w(r),null}}async Load(e,a,s=null,t){try{const r={};let u="",n="";for(let c=0;c<a.KeyValuePairs.length;c++){const o=e.Fields.find(D=>D.Name.trim().toLowerCase()===a.KeyValuePairs[c].FieldName.trim().toLowerCase()).EntityFieldInfo,l=a.GetValueByIndex(c),y=o.GraphQLType;if(n.length>0&&(n+=", "),n+=`$${o.CodeName}: ${y}!`,u.length>0&&(u+=", "),u+=`${o.CodeName}: $${o.CodeName}`,o.TSType===N.Number){if(isNaN(a.GetValueByIndex(c)))throw new Error(`Primary Key value ${l} (${o.Name}) is not a valid number`);r[o.CodeName]=parseInt(l)}else r[o.CodeName]=l}const i=s&&s.length>0?this.getRelatedEntityString(e.EntityInfo,s):"",m=new I,p=h`query Single${e.EntityInfo.ClassName}${i.length>0?"Full":""} (${n}) {
129
+ `;for(let c=0;c<i.length;c++){const o=i[c];let l=o.Value;if(l)switch(o.EntityFieldInfo.TSType){case E.Date:l=l.getTime();break;case E.Boolean:typeof l!="boolean"&&(l=parseInt(l)!==0);break;case E.Number:if(typeof l!="number"){const y=Number(l);isNaN(y)||(l=y)}break}l===null&&o.EntityFieldInfo.AllowsNull===!1&&(o.EntityFieldInfo.DefaultValue!==null?l=o.EntityFieldInfo.DefaultValue:o.FieldType===E.Number||o.FieldType===E.Boolean?l=0:l=""),r.input[o.CodeName]=l}if(u.trim().toLowerCase()==="update"&&s.SkipOldValuesCheck===!1){const c=[];e.Fields.forEach(o=>{let l=null;o.OldValue!==null&&o.OldValue!==void 0&&(o.EntityFieldInfo.TSType===E.Date?l=o.OldValue.getTime().toString():o.EntityFieldInfo.TSType===E.Boolean?l=o.OldValue===!0?"1":"0":typeof o.OldValue!="string"?l=o.OldValue.toString():l=o.OldValue),c.push({Key:o.CodeName,Value:l})}),r.input.OldValues___=c}if(e.TransactionGroup){const c=[{varName:"input",inputType:n+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new ue(e,t.Type==="create"?"Create":"Update",f,r,{mutationName:n,mutationInputTypes:c},(o,l)=>{t.EndedAt=new Date,l&&o?(t.Success=!0,t.NewValues=this.ConvertBackToMJFields(o)):(t.Success=!1,t.Message="Transaction failed")})),!0}else{const c=await this.ExecuteGQL(d,r);if(c&&c[u+e.EntityInfo.ClassName])return t.Success=!0,t.EndedAt=new Date,t.NewValues=this.ConvertBackToMJFields(c[u+e.EntityInfo.ClassName]),t.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(r){return t.Success=!1,t.EndedAt=new Date,t.Message=r.response?.errors?.length>0?r.response.errors[0].message:r.message,w(r),null}}async Load(e,a,s=null,t){try{const r={};let u="",n="";for(let c=0;c<a.KeyValuePairs.length;c++){const o=e.Fields.find(D=>D.Name.trim().toLowerCase()===a.KeyValuePairs[c].FieldName.trim().toLowerCase()).EntityFieldInfo,l=a.GetValueByIndex(c),y=o.GraphQLType;if(n.length>0&&(n+=", "),n+=`$${o.CodeName}: ${y}!`,u.length>0&&(u+=", "),u+=`${o.CodeName}: $${o.CodeName}`,o.TSType===E.Number){if(isNaN(a.GetValueByIndex(c)))throw new Error(`Primary Key value ${l} (${o.Name}) is not a valid number`);r[o.CodeName]=parseInt(l)}else r[o.CodeName]=l}const i=s&&s.length>0?this.getRelatedEntityString(e.EntityInfo,s):"",m=new I,f=p`query Single${e.EntityInfo.ClassName}${i.length>0?"Full":""} (${n}) {
122
130
  ${e.EntityInfo.ClassName}(${u}) {
123
131
  ${e.Fields.filter(c=>!c.EntityFieldInfo.IsBinaryFieldType).map(c=>c.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?c.CodeName.replace("__mj_","_mj__"):c.CodeName).join(`
124
132
  `)}
125
133
  ${i}
126
134
  }
127
135
  }
128
- `,d=await this.ExecuteGQL(p,r);return d&&d[e.EntityInfo.ClassName]?this.ConvertBackToMJFields(d[e.EntityInfo.ClassName]):null}catch(r){return w(r),null}}ConvertBackToMJFields(e){return new I().ReverseMapFields(e),e}getRelatedEntityString(e,a){let s="";for(let t=0;t<e.RelatedEntities.length;t++)if(a.indexOf(e.RelatedEntities[t].RelatedEntity)>=0){const r=e.RelatedEntities[t],u=this.Entities.find(i=>i.ID===r.RelatedEntityID);let n="";r.Type.toLowerCase().trim()==="many to many"?n=`${r.RelatedEntityCodeName}_${r.JoinEntityJoinField.replace(/\s/g,"")}`:n=`${r.RelatedEntityCodeName}_${r.RelatedEntityJoinField.replace(/\s/g,"")}`,s+=`
136
+ `,d=await this.ExecuteGQL(f,r);return d&&d[e.EntityInfo.ClassName]?this.ConvertBackToMJFields(d[e.EntityInfo.ClassName]):null}catch(r){return w(r),null}}ConvertBackToMJFields(e){return new I().ReverseMapFields(e),e}getRelatedEntityString(e,a){let s="";for(let t=0;t<e.RelatedEntities.length;t++)if(a.indexOf(e.RelatedEntities[t].RelatedEntity)>=0){const r=e.RelatedEntities[t],u=this.Entities.find(i=>i.ID===r.RelatedEntityID);let n="";r.Type.toLowerCase().trim()==="many to many"?n=`${r.RelatedEntityCodeName}_${r.JoinEntityJoinField.replace(/\s/g,"")}`:n=`${r.RelatedEntityCodeName}_${r.RelatedEntityJoinField.replace(/\s/g,"")}`,s+=`
129
137
  ${n} {
130
138
  ${u.Fields.map(i=>i.CodeName).join(`
131
139
  `)}
132
140
  }
133
141
  `}return s}async Delete(e,a,s){const t=new oe;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={},u=[];let n="",i="",m="";for(let o of e.PrimaryKey.KeyValuePairs){const l=e.Fields.find(y=>y.Name.trim().toLowerCase()===o.FieldName.trim().toLowerCase());r[l.CodeName]=l.Value,u.push({varName:l.CodeName,inputType:l.EntityFieldInfo.GraphQLType+"!"}),n.length>0&&(n+=", "),n+=`${l.CodeName}: $${l.CodeName}`,i.length>0&&(i+=", "),i+=`$${l.CodeName}: ${l.EntityFieldInfo.GraphQLType}!`,m.length>0&&(m+=`
134
- `),m+=`${l.CodeName}`}u.push({varName:"options___",inputType:"DeleteOptionsInput!"}),r.options___=a||{SkipEntityAIActions:!1,SkipEntityActions:!1};const p="Delete"+e.EntityInfo.ClassName,d=h`${p}(${n}, options___: $options___) {
142
+ `),m+=`${l.CodeName}`}u.push({varName:"options___",inputType:"DeleteOptionsInput!"}),r.options___=a||{SkipEntityAIActions:!1,SkipEntityActions:!1};const f="Delete"+e.EntityInfo.ClassName,d=p`${f}(${n}, options___: $options___) {
135
143
  ${m}
136
144
  }
137
- `,c=h`mutation ${p} (${i}, $options___: DeleteOptionsInput!) {
145
+ `,c=p`mutation ${f} (${i}, $options___: DeleteOptionsInput!) {
138
146
  ${d}
139
147
  }
140
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new ue(e,"Delete",d,r,{mutationName:p,mutationInputTypes:u},(o,l)=>{if(t.EndedAt=new Date,l&&o){let y=!0;for(const D of e.PrimaryKey.KeyValuePairs)D.Value!==o[D.FieldName]&&(y=!1);y?t.Success=!0:(t.Success=!1,t.Message="Transaction failed to commit")}else t.Success=!1,t.Message="Transaction failed to commit"})),!0;{const o=await this.ExecuteGQL(c,r);if(o&&o[p]){const l=o[p];for(let y of e.PrimaryKey.KeyValuePairs){let D=l[y.FieldName],S=y.Value;if(typeof S=="number"&&(S=S.toString()),typeof D=="number"&&(D=D.toString()),S!==D)throw new Error(`Primary key value mismatch in server Delete response. Field: ${y.FieldName}, Original: ${S}, Returned: ${D}`)}return t.Success=!0,t.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(r){return t.EndedAt=new Date,t.Success=!1,t.Message=r.response?.errors?.length>0?r.response.errors[0].message:r.message,w(r),!1}}async GetDatasetByName(e,a){const s=h`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
148
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new ue(e,"Delete",d,r,{mutationName:f,mutationInputTypes:u},(o,l)=>{if(t.EndedAt=new Date,l&&o){let y=!0;for(const D of e.PrimaryKey.KeyValuePairs)D.Value!==o[D.FieldName]&&(y=!1);y?t.Success=!0:(t.Success=!1,t.Message="Transaction failed to commit")}else t.Success=!1,t.Message="Transaction failed to commit"})),!0;{const o=await this.ExecuteGQL(c,r);if(o&&o[f]){const l=o[f];for(let y of e.PrimaryKey.KeyValuePairs){let D=l[y.FieldName],S=y.Value;if(typeof S=="number"&&(S=S.toString()),typeof D=="number"&&(D=D.toString()),S!==D)throw new Error(`Primary key value mismatch in server Delete response. Field: ${y.FieldName}, Original: ${S}, Returned: ${D}`)}return t.Success=!0,t.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(r){return t.EndedAt=new Date,t.Success=!1,t.Message=r.response?.errors?.length>0?r.response.errors[0].message:r.message,w(r),!1}}async GetDatasetByName(e,a){const s=p`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
141
149
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
142
150
  DatasetID
143
151
  DatasetName
@@ -146,7 +154,7 @@ var ye=Object.defineProperty;var f=(E,e)=>ye(E,"name",{value:e,configurable:!0})
146
154
  LatestUpdateDate
147
155
  Results
148
156
  }
149
- }`,t=await this.ExecuteGQL(s,{DatasetName:e,ItemFilters:a});return t&&t.GetDatasetByName&&t.GetDatasetByName.Success?{DatasetID:t.GetDatasetByName.DatasetID,DatasetName:t.GetDatasetByName.DatasetName,Success:t.GetDatasetByName.Success,Status:t.GetDatasetByName.Status,LatestUpdateDate:new Date(t.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(t.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}async GetDatasetStatusByName(e,a){const s=h`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
157
+ }`,t=await this.ExecuteGQL(s,{DatasetName:e,ItemFilters:a});return t&&t.GetDatasetByName&&t.GetDatasetByName.Success?{DatasetID:t.GetDatasetByName.DatasetID,DatasetName:t.GetDatasetByName.DatasetName,Success:t.GetDatasetByName.Success,Status:t.GetDatasetByName.Status,LatestUpdateDate:new Date(t.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(t.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}async GetDatasetStatusByName(e,a){const s=p`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
150
158
  GetDatasetStatusByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
151
159
  DatasetID
152
160
  DatasetName
@@ -155,22 +163,22 @@ var ye=Object.defineProperty;var f=(E,e)=>ye(E,"name",{value:e,configurable:!0})
155
163
  LatestUpdateDate
156
164
  EntityUpdateDates
157
165
  }
158
- }`,t=await this.ExecuteGQL(s,{DatasetName:e,ItemFilters:a});return t&&t.GetDatasetStatusByName&&t.GetDatasetStatusByName.Success?{DatasetID:t.GetDatasetStatusByName.DatasetID,DatasetName:t.GetDatasetStatusByName.DatasetName,Success:t.GetDatasetStatusByName.Success,Status:t.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(t.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(t.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new V(this)}async GetRecordFavoriteStatus(e,a,s){if(!s.Validate().IsValid)return!1;const r=this.Entities.find(i=>i.Name===a);if(!r)throw new Error(`Entity ${a} not found in metadata`);const u=h`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
166
+ }`,t=await this.ExecuteGQL(s,{DatasetName:e,ItemFilters:a});return t&&t.GetDatasetStatusByName&&t.GetDatasetStatusByName.Success?{DatasetID:t.GetDatasetStatusByName.DatasetID,DatasetName:t.GetDatasetStatusByName.DatasetName,Success:t.GetDatasetStatusByName.Success,Status:t.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(t.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(t.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new V(this)}async GetRecordFavoriteStatus(e,a,s){if(!s.Validate().IsValid)return!1;const r=this.Entities.find(i=>i.Name===a);if(!r)throw new Error(`Entity ${a} not found in metadata`);const u=p`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
159
167
  GetRecordFavoriteStatus(params: $params) {
160
168
  Success
161
169
  IsFavorite
162
170
  }
163
- }`,n=await this.ExecuteGQL(u,{params:{UserID:e,EntityID:r.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.KeyValuePairs)}}});if(n&&n.GetRecordFavoriteStatus&&n.GetRecordFavoriteStatus.Success)return n.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,a,s,t,r){const u=this.Entities.find(m=>m.Name===a);if(!u)throw new Error(`Entity ${a} not found in metadata`);const n=h`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
171
+ }`,n=await this.ExecuteGQL(u,{params:{UserID:e,EntityID:r.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.KeyValuePairs)}}});if(n&&n.GetRecordFavoriteStatus&&n.GetRecordFavoriteStatus.Success)return n.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,a,s,t,r){const u=this.Entities.find(m=>m.Name===a);if(!u)throw new Error(`Entity ${a} not found in metadata`);const n=p`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
164
172
  SetRecordFavoriteStatus(params: $params){
165
173
  Success
166
174
  }
167
- }`,i=await this.ExecuteGQL(n,{params:{UserID:e,EntityID:u.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.KeyValuePairs)},IsFavorite:t}});if(i&&i.SetRecordFavoriteStatus!==null)return i.SetRecordFavoriteStatus.Success}async GetEntityRecordName(e,a){if(!e||!a||a.KeyValuePairs?.length===0)return null;const s=h`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
175
+ }`,i=await this.ExecuteGQL(n,{params:{UserID:e,EntityID:u.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.KeyValuePairs)},IsFavorite:t}});if(i&&i.SetRecordFavoriteStatus!==null)return i.SetRecordFavoriteStatus.Success}async GetEntityRecordName(e,a){if(!e||!a||a.KeyValuePairs?.length===0)return null;const s=p`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
168
176
  GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
169
177
  Success
170
178
  Status
171
179
  RecordName
172
180
  }
173
- }`,t=await this.ExecuteGQL(s,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(a.KeyValuePairs)}});if(t&&t.GetEntityRecordName&&t.GetEntityRecordName.Success)return t.GetEntityRecordName.RecordName}async GetEntityRecordNames(e){if(!e)return null;const a=h`query GetEntityRecordNamesQuery ($info: [EntityRecordNameInput!]!) {
181
+ }`,t=await this.ExecuteGQL(s,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(a.KeyValuePairs)}});if(t&&t.GetEntityRecordName&&t.GetEntityRecordName.Success)return t.GetEntityRecordName.RecordName}async GetEntityRecordNames(e){if(!e)return null;const a=p`query GetEntityRecordNamesQuery ($info: [EntityRecordNameInput!]!) {
174
182
  GetEntityRecordNames(info: $info) {
175
183
  Success
176
184
  Status
@@ -183,16 +191,16 @@ var ye=Object.defineProperty;var f=(E,e)=>ye(E,"name",{value:e,configurable:!0})
183
191
  EntityName
184
192
  RecordName
185
193
  }
186
- }`,s=await this.ExecuteGQL(a,{info:e.map(t=>({EntityName:t.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.CompositeKey.KeyValuePairs)}}))});if(s&&s.GetEntityRecordNames)return s.GetEntityRecordNames}static async ExecuteGQL(e,a,s=!0){return R.Instance.ExecuteGQL(e,a,s)}async ExecuteGQL(e,a,s=!0){try{return await this._client.request(e,a)}catch(t){if(t&&t.response&&t.response.errors?.length>0)if(t.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(s)return await this.RefreshToken(),await this.ExecuteGQL(e,a,!1);throw w("JWT_EXPIRED and refreshTokenIfNeeded is false"),t}else throw t;else throw w(t),t}}async RefreshToken(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e)this._configData.Token=e,this._client=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey);else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static async RefreshToken(){return R.Instance.RefreshToken()}CreateNewGraphQLClient(e,a,s,t){const r={"x-session-id":s};return a&&(r.authorization="Bearer "+a),t&&(r["x-mj-api-key"]=t),new ie(e,{headers:r})}userInfoString(){return this.infoString(new ne(null,null))}userRoleInfoString(){return this.infoString(new we(null))}infoString(e){let a="";const s=Object.keys(e);for(const t of s)t.startsWith("__mj_")?a+=t.replace("__mj_","_mj__")+`
194
+ }`,s=await this.ExecuteGQL(a,{info:e.map(t=>({EntityName:t.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.CompositeKey.KeyValuePairs)}}))});if(s&&s.GetEntityRecordNames)return s.GetEntityRecordNames}static async ExecuteGQL(e,a,s=!0){return N.Instance.ExecuteGQL(e,a,s)}async ExecuteGQL(e,a,s=!0){try{return await this._client.request(e,a)}catch(t){if(t&&t.response&&t.response.errors?.length>0)if(t.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(s)return await this.RefreshToken(),await this.ExecuteGQL(e,a,!1);throw w("JWT_EXPIRED and refreshTokenIfNeeded is false"),t}else throw t;else throw w(t),t}}async RefreshToken(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e)this._configData.Token=e,this._client=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey);else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static async RefreshToken(){return N.Instance.RefreshToken()}CreateNewGraphQLClient(e,a,s,t){const r={"x-session-id":s};return a&&(r.authorization="Bearer "+a),t&&(r["x-mj-api-key"]=t),new ie(e,{headers:r})}userInfoString(){return this.infoString(new ne(null,null))}userRoleInfoString(){return this.infoString(new we(null))}infoString(e){let a="";const s=Object.keys(e);for(const t of s)t.startsWith("__mj_")?a+=t.replace("__mj_","_mj__")+`
187
195
  `:t.startsWith("_")||(a+=t+`
188
- `);return a}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new T),this._localStorageProvider}get Metadata(){return this}PushStatusUpdates(e=null){e||(e=this.sessionId),this._wsClient||(this._wsClient=ge({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}}));const a=this._pushStatusRequests.find(r=>r.sessionId===e);if(a)return a.observable;const s=h`subscription StatusUpdates($sessionId: String!) {
196
+ `);return a}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new T),this._localStorageProvider}get Metadata(){return this}PushStatusUpdates(e=null){e||(e=this.sessionId),this._wsClient||(this._wsClient=ge({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}}));const a=this._pushStatusRequests.find(r=>r.sessionId===e);if(a)return a.observable;const s=p`subscription StatusUpdates($sessionId: String!) {
189
197
  statusUpdates(sessionId: $sessionId) {
190
198
  date
191
199
  message
192
200
  sessionId
193
201
  }
194
202
  }
195
- `,t=new Ne(r=>(this._wsClient.subscribe({query:s,variables:{sessionId:e}},{next:u=>r.next(u.data.statusUpdates),error:u=>r.error(u),complete:()=>r.complete()}),()=>{console.log("would unsub here")}));return this._pushStatusRequests.push({sessionId:e,observable:t}),t}};f(R,"GraphQLDataProvider");let C=R;const b=class b{constructor(){this._localStorage={}}async getItem(e){return new Promise(a=>{this._localStorage.hasOwnProperty(e)?a(this._localStorage[e]):a(null)})}async setItem(e,a){return new Promise(s=>{this._localStorage[e]=a,s()})}async remove(e){return new Promise(a=>{this._localStorage.hasOwnProperty(e)&&delete this._localStorage[e],a()})}};f(b,"BrowserStorageProviderBase");let G=b;const Ce="MJ_Metadata",g="Metadata_KVPairs",J=class J extends G{constructor(){super(),this.dbPromise=Ee(Ce,1,{upgrade(e){e.objectStoreNames.contains(g)||e.createObjectStore(g)}})}async setItem(e,a){const t=(await this.dbPromise).transaction(g,"readwrite");await t.objectStore(g).put(a,e),await t.done}async getItem(e){return await(await this.dbPromise).transaction(g).objectStore(g).get(e)}async remove(e){const s=(await this.dbPromise).transaction(g,"readwrite");await s.objectStore(g).delete(e),await s.done}};f(J,"BrowserIndexedDBStorageProvider");let T=J;async function Fe(E){const e=new C;return Re(e),await e.Config(E),Ie.Instance.RaiseEvent({event:Ve.LoggedIn,eventCode:null,component:this,args:null}),e}f(Fe,"setupGraphQLClient");const j=class j{};f(j,"SyncRolesAndUsersResult");let $=j;const W=class W{};f(W,"RoleInput");let _=W;const z=class z{};f(z,"UserInput");let v=z;const H=class H{};f(H,"RolesAndUsersInput");let L=H;var de=(E=>(E.Create="Create",E.Update="Update",E.CreateOrUpdate="CreateOrUpdate",E.Delete="Delete",E.DeleteWithFilter="DeleteWithFilter",E))(de||{});const X=class X{};f(X,"ActionItemInput");let P=X;const Z=class Z{constructor(){this.Results=[]}};f(Z,"SyncDataResult");let M=Z;const Y=class Y{};f(Y,"ActionItemOutput");let U=Y;const ee=class ee{get Client(){return this._client}constructor(e,a,s,t){const r={"x-session-id":s};a&&(r.authorization="Bearer "+a),t&&(r["x-mj-api-key"]=t),this._client=new ie(e,{headers:r})}async GetData(e,a){try{const t=await this.Client.request(`query GetData($input: GetDataInputType!) {
203
+ `,t=new Ee(r=>(this._wsClient.subscribe({query:s,variables:{sessionId:e}},{next:u=>r.next(u.data.statusUpdates),error:u=>r.error(u),complete:()=>r.complete()}),()=>{console.log("would unsub here")}));return this._pushStatusRequests.push({sessionId:e,observable:t}),t}};h(N,"GraphQLDataProvider");let C=N;const b=class b{constructor(){this._localStorage={}}async getItem(e){return new Promise(a=>{this._localStorage.hasOwnProperty(e)?a(this._localStorage[e]):a(null)})}async setItem(e,a){return new Promise(s=>{this._localStorage[e]=a,s()})}async remove(e){return new Promise(a=>{this._localStorage.hasOwnProperty(e)&&delete this._localStorage[e],a()})}};h(b,"BrowserStorageProviderBase");let G=b;const Ce="MJ_Metadata",g="Metadata_KVPairs",J=class J extends G{constructor(){super(),this.dbPromise=Re(Ce,1,{upgrade(e){e.objectStoreNames.contains(g)||e.createObjectStore(g)}})}async setItem(e,a){const t=(await this.dbPromise).transaction(g,"readwrite");await t.objectStore(g).put(a,e),await t.done}async getItem(e){return await(await this.dbPromise).transaction(g).objectStore(g).get(e)}async remove(e){const s=(await this.dbPromise).transaction(g,"readwrite");await s.objectStore(g).delete(e),await s.done}};h(J,"BrowserIndexedDBStorageProvider");let T=J;async function Fe(R){const e=new C;return Ne(e),await e.Config(R),Ie.Instance.RaiseEvent({event:Ve.LoggedIn,eventCode:null,component:this,args:null}),e}h(Fe,"setupGraphQLClient");const j=class j{};h(j,"SyncRolesAndUsersResult");let $=j;const W=class W{};h(W,"RoleInput");let L=W;const z=class z{};h(z,"UserInput");let _=z;const H=class H{};h(H,"RolesAndUsersInput");let v=H;var de=(R=>(R.Create="Create",R.Update="Update",R.CreateOrUpdate="CreateOrUpdate",R.Delete="Delete",R.DeleteWithFilter="DeleteWithFilter",R))(de||{});const X=class X{};h(X,"ActionItemInput");let P=X;const Z=class Z{constructor(){this.Results=[]}};h(Z,"SyncDataResult");let x=Z;const Y=class Y{};h(Y,"ActionItemOutput");let M=Y;const ee=class ee{get Client(){return this._client}constructor(e,a,s,t){const r={"x-session-id":s};a&&(r.authorization="Bearer "+a),t&&(r["x-mj-api-key"]=t),this._client=new ie(e,{headers:r})}async GetData(e,a){try{const t=await this.Client.request(`query GetData($input: GetDataInputType!) {
196
204
  GetData(input: $input) {
197
205
  Success
198
206
  ErrorMessages
@@ -250,5 +258,5 @@ var ye=Object.defineProperty;var f=(E,e)=>ye(E,"name",{value:e,configurable:!0})
250
258
  SyncRolesAndUsers(data: $data) {
251
259
  Success
252
260
  }
253
- }`,{data:e});return s&&s.SyncRolesAndUsers?s.SyncRolesAndUsers:{Success:!1}}catch(a){return w(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${a}`),{Success:!1}}}};f(ee,"GraphQLSystemUserClient");let x=ee;const te=class te{};f(te,"GetDataOutput");let A=te;const se=class se{};f(se,"SimpleRemoteEntityOutput");let Q=se;const ae=class ae{};f(ae,"SimpleRemoteEntity");let K=ae;const re=class re{};f(re,"SimpleRemoteEntityField");let k=re;export{P as ActionItemInput,U as ActionItemOutput,I as FieldMapper,A as GetDataOutput,C as GraphQLDataProvider,F as GraphQLProviderConfigData,x as GraphQLSystemUserClient,V as GraphQLTransactionGroup,_ as RoleInput,L as RolesAndUsersInput,K as SimpleRemoteEntity,k as SimpleRemoteEntityField,Q as SimpleRemoteEntityOutput,de as SyncDataAction,M as SyncDataResult,$ as SyncRolesAndUsersResult,v as UserInput,Qe as gql,Fe as setupGraphQLClient};
261
+ }`,{data:e});return s&&s.SyncRolesAndUsers?s.SyncRolesAndUsers:{Success:!1}}catch(a){return w(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${a}`),{Success:!1}}}};h(ee,"GraphQLSystemUserClient");let U=ee;const te=class te{};h(te,"GetDataOutput");let Q=te;const se=class se{};h(se,"SimpleRemoteEntityOutput");let B=se;const ae=class ae{};h(ae,"SimpleRemoteEntity");let A=ae;const re=class re{};h(re,"SimpleRemoteEntityField");let K=re;export{P as ActionItemInput,M as ActionItemOutput,I as FieldMapper,Q as GetDataOutput,C as GraphQLDataProvider,F as GraphQLProviderConfigData,U as GraphQLSystemUserClient,V as GraphQLTransactionGroup,L as RoleInput,v as RolesAndUsersInput,A as SimpleRemoteEntity,K as SimpleRemoteEntityField,B as SimpleRemoteEntityOutput,de as SyncDataAction,x as SyncDataResult,$ as SyncRolesAndUsersResult,_ as UserInput,Be as gql,Fe as setupGraphQLClient};
254
262
  //# sourceMappingURL=index.mjs.map