@memberjunction/graphql-dataprovider 2.29.2 → 2.31.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.cjs +60 -46
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +14 -2
- package/dist/index.d.mts +14 -2
- package/dist/index.mjs +57 -43
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var oe=Object.defineProperty;var
|
|
1
|
+
"use strict";var oe=Object.defineProperty;var f=(w,e)=>oe(w,"name",{value:e,configurable:!0});var m=require("graphql-request"),y=require("@memberjunction/core"),ne=require("@memberjunction/core-entities"),ue=require("@tempfix/idb"),le=require("rxjs"),ce=require("graphql-ws"),ye=require("uuid"),I=require("@memberjunction/global");const O=class O{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(O,"FieldMapper");let S=O;const K=class K extends y.TransactionGroupBase{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=m.gql`
|
|
2
2
|
mutation ExecuteTransactionGroup($group: TransactionInputType!) {
|
|
3
3
|
ExecuteTransactionGroup(group: $group) {
|
|
4
4
|
Success
|
|
@@ -6,15 +6,15 @@
|
|
|
6
6
|
ResultsJSON
|
|
7
7
|
}
|
|
8
8
|
}
|
|
9
|
-
`,
|
|
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,o=[];for(let n=0;n<this.PendingTransactions.length;n++){const i=r.ResultsJSON[n],p=I.SafeJSONParse(i),g=this.PendingTransactions[n];o.push(new y.TransactionResult(g,p,p!==null))}return o}else throw new Error("Failed to execute transaction group")}};f(K,"GraphQLTransactionGroup");let C=K;const k=class k extends y.ProviderConfigDataBase{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,o,n,i){super({Token:e,URL:a,WSURL:s,MJAPIKey:i,RefreshTokenFunction:t},r,o,n)}};f(k,"GraphQLProviderConfigData");let G=k;const E=class E extends y.ProviderBase{constructor(){super(),this._innerCurrentUserQueryString=`CurrentUser {
|
|
10
10
|
${this.userInfoString()}
|
|
11
11
|
UserRoles_UserIDArray {
|
|
12
12
|
${this.userRoleInfoString()}
|
|
13
13
|
}
|
|
14
14
|
}
|
|
15
|
-
`,this._currentUserQuery=
|
|
15
|
+
`,this._currentUserQuery=m.gql`query CurrentUserAndRoles {
|
|
16
16
|
${this._innerCurrentUserQueryString}
|
|
17
|
-
}`,this._wsClient=null,this._pushStatusRequests=[],
|
|
17
|
+
}`,this._wsClient=null,this._pushStatusRequests=[],E._instance||(E._instance=this)}static get Instance(){return E._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 ye.v4()}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)):(E.Instance._sessionId===void 0&&(E.Instance._sessionId=s),E.Instance._configData=e,E.Instance._client||(E.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,E.Instance._sessionId,e.MJAPIKey))),super.Config(e)}catch(s){throw y.LogError(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 y.UserInfo(this,{...a,UserRoles:s})}}async RunReport(e,a){const s=m.gql`
|
|
18
18
|
query GetReportDataQuery ($ReportID: String!) {
|
|
19
19
|
GetReportData(ReportID: $ReportID) {
|
|
20
20
|
Success
|
|
@@ -23,28 +23,30 @@
|
|
|
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,
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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,e.CategoryID,e.CategoryName,a);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryName,a);throw new Error("No QueryID or QueryName provided to RunQuery")}async RunQueryByID(e,a,s,t){const r=m.gql`
|
|
27
|
+
query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryName: String) {
|
|
28
|
+
GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryName: $CategoryName) {
|
|
29
|
+
${this.QueryReturnFieldList}
|
|
30
|
+
}
|
|
30
31
|
}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
32
|
+
`,o={QueryID:e};a!==void 0&&(o.CategoryID=a),s!==void 0&&(o.CategoryName=s);const n=await this.ExecuteGQL(r,o);if(n&&n.GetQueryData)return this.TransformQueryPayload(n.GetQueryData)}async RunQueryByName(e,a,s,t){const r=m.gql`
|
|
33
|
+
query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryName: String) {
|
|
34
|
+
GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryName: $CategoryName) {
|
|
35
|
+
${this.QueryReturnFieldList}
|
|
36
|
+
}
|
|
35
37
|
}
|
|
36
|
-
|
|
38
|
+
`,o={QueryName:e,CategoryID:a,CategoryName:s},n=await this.ExecuteGQL(r,o);if(n&&n.GetQueryDataByName)return this.TransformQueryPayload(n.GetQueryDataByName)}get QueryReturnFieldList(){return`
|
|
37
39
|
Success
|
|
38
40
|
QueryID
|
|
39
41
|
QueryName
|
|
40
42
|
Results
|
|
41
43
|
RowCount
|
|
42
44
|
ExecutionTime
|
|
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(
|
|
45
|
+
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 y.LogError(`Error transforming query payload: ${a}`),null}}async RunView(e,a){try{let s="",t="";if(e){const r={};let o,n;if(e.ViewEntity)n=e.ViewEntity,o=n.Entity;else{const{entityName:u,v:l}=await this.getEntityNameAndUserView(e,a);n=l,o=u}const i=this.Entities.find(u=>u.Name===o);if(!i)throw new Error(`Entity ${o} not found in metadata`);let p=!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):(p=!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),p||(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 g=this.getViewRunTimeFieldList(i,n,e,p),d=m.gql`
|
|
44
46
|
query RunViewQuery ($input: ${t}!) {
|
|
45
47
|
${s}(input: $input) {
|
|
46
48
|
Results {
|
|
47
|
-
${
|
|
49
|
+
${g.join(`
|
|
48
50
|
`)}
|
|
49
51
|
}
|
|
50
52
|
UserViewRunID
|
|
@@ -54,7 +56,7 @@
|
|
|
54
56
|
Success
|
|
55
57
|
ErrorMessage
|
|
56
58
|
}
|
|
57
|
-
}`,c=await this.ExecuteGQL(
|
|
59
|
+
}`,c=await this.ExecuteGQL(d,{input:r});if(c&&c[s]){const u=c[s].Results;if(u&&u.length>0){const l=i.Fields.filter(D=>D.CodeName!==D.Name&&D.CodeName!==void 0);u.forEach(D=>{this.ConvertBackToMJFields(D),l.forEach(h=>{D[h.Name]=D[h.CodeName]})})}return c[s]}}else throw"No parameters passed to RunView";return null}catch(s){throw y.LogError(s),s}}async RunViews(e,a){try{let s=[],t=[],r=[];for(const i of e){let p="",g="";const d={};let c=null,u=null;if(i.ViewEntity)u=i.ViewEntity,c=u.Get("Entity");else{const{entityName:h,v:N}=await this.getEntityNameAndUserView(i,a);u=N,c=h}const l=this.Entities.find(h=>h.Name===c);if(!l)throw new Error(`Entity ${c} not found in metadata`);t.push(l);let D=!1;i.ViewID?(p=`Run${l.ClassName}ViewByID`,g="RunViewByIDInput",d.ViewID=i.ViewID):i.ViewName?(p=`Run${l.ClassName}ViewByName`,g="RunViewByNameInput",d.ViewName=i.ViewName):(D=!0,p=`Run${l.ClassName}DynamicView`,g="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),D||(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,u,i,D))}const o=m.gql`
|
|
58
60
|
query RunViewsQuery ($input: [RunViewGenericInput!]!) {
|
|
59
61
|
RunViews(input: $input) {
|
|
60
62
|
Results {
|
|
@@ -69,7 +71,7 @@
|
|
|
69
71
|
Success
|
|
70
72
|
ErrorMessage
|
|
71
73
|
}
|
|
72
|
-
}`,n=await this.ExecuteGQL(
|
|
74
|
+
}`,n=await this.ExecuteGQL(o,{input:s});if(n&&n.RunViews){const i=n.RunViews;for(const[p,g]of i.entries())g.Results=g.Results.map(d=>{let c=JSON.parse(d.Data);return this.ConvertBackToMJFields(c),c});return i}return null}catch(s){throw y.LogError(s),s}}async getEntityNameAndUserView(e,a){let s,t;if(e.EntityName)s=e.EntityName;else if(e.ViewID)t=await ne.ViewInfo.GetViewEntity(e.ViewID,a),s=t.Entity;else if(e.ViewName)t=await ne.ViewInfo.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=[],o=new S;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(o.MapFieldName(n))})}else if(t)e.Fields.forEach(n=>{n.IsBinaryFieldType||r.push(o.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(o.MapFieldName(n.EntityField.CodeName))})}return r}get ProviderType(){return y.ProviderType.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,o)=>r.ChangedAt>o.ChangedAt?-1:1):null}catch(s){throw y.LogError(s),s}}async GetRecordDependencies(e,a){try{const s=m.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
73
75
|
GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
|
|
74
76
|
EntityName
|
|
75
77
|
RelatedEntityName
|
|
@@ -81,7 +83,7 @@
|
|
|
81
83
|
}
|
|
82
84
|
}
|
|
83
85
|
}
|
|
84
|
-
}`,t={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(
|
|
86
|
+
}`,t={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(a.KeyValuePairs)}};return(await this.ExecuteGQL(s,t))?.GetRecordDependencies}catch(s){throw y.LogError(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=m.gql`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
|
|
85
87
|
GetRecordDuplicates(params: $params) {
|
|
86
88
|
Status
|
|
87
89
|
ErrorMessage
|
|
@@ -103,7 +105,7 @@
|
|
|
103
105
|
}
|
|
104
106
|
}
|
|
105
107
|
}
|
|
106
|
-
}`;let t={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(
|
|
108
|
+
}`;let t={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(o=>o.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=m.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
|
|
107
109
|
MergeRecords(request: $request) {
|
|
108
110
|
Success
|
|
109
111
|
OverallStatus
|
|
@@ -120,32 +122,32 @@
|
|
|
120
122
|
Message
|
|
121
123
|
}
|
|
122
124
|
}
|
|
123
|
-
}`,t={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(
|
|
124
|
-
${e.Fields.map(c=>
|
|
125
|
+
}`,t={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(s,{request:t}))?.MergeRecords}catch(s){return y.LogError(s),{Success:!1,OverallStatus:s&&s.message?s.message:s,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,a,s){const t=new y.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const r={input:{}},o=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=`${o}${e.EntityInfo.ClassName}`,i=e.Fields.filter(c=>!c.ReadOnly||c.IsPrimaryKey&&e.IsSaved),p=new S,g=` ${n}(input: $input) {
|
|
126
|
+
${e.Fields.map(c=>p.MapFieldName(c.CodeName)).join(`
|
|
125
127
|
`)}
|
|
126
|
-
}`,
|
|
127
|
-
${
|
|
128
|
+
}`,d=m.gql`mutation ${o}${e.EntityInfo.ClassName} ($input: ${n}Input!) {
|
|
129
|
+
${g}
|
|
128
130
|
}
|
|
129
|
-
`;for(let c=0;c<i.length;c++){const
|
|
130
|
-
${e.EntityInfo.ClassName}(${
|
|
131
|
+
`;for(let c=0;c<i.length;c++){const u=i[c];let l=u.Value;if(l)switch(u.EntityFieldInfo.TSType){case y.EntityFieldTSType.Date:l=l.getTime();break;case y.EntityFieldTSType.Boolean:typeof l!="boolean"&&(l=parseInt(l)!==0);break;case y.EntityFieldTSType.Number:if(typeof l!="number"){const D=Number(l);isNaN(D)||(l=D)}break}l===null&&u.EntityFieldInfo.AllowsNull===!1&&(u.EntityFieldInfo.DefaultValue!==null?l=u.EntityFieldInfo.DefaultValue:u.FieldType===y.EntityFieldTSType.Number||u.FieldType===y.EntityFieldTSType.Boolean?l=0:l=""),r.input[u.CodeName]=l}if(o.trim().toLowerCase()==="update"&&s.SkipOldValuesCheck===!1){const c=[];e.Fields.forEach(u=>{let l=null;u.OldValue!==null&&u.OldValue!==void 0&&(u.EntityFieldInfo.TSType===y.EntityFieldTSType.Date?l=u.OldValue.getTime().toString():u.EntityFieldInfo.TSType===y.EntityFieldTSType.Boolean?l=u.OldValue===!0?"1":"0":typeof u.OldValue!="string"?l=u.OldValue.toString():l=u.OldValue),c.push({Key:u.CodeName,Value:l})}),r.input.OldValues___=c}if(e.TransactionGroup){const c=[{varName:"input",inputType:n+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new y.TransactionItem(e,t.Type==="create"?"Create":"Update",g,r,{mutationName:n,mutationInputTypes:c},(u,l)=>{t.EndedAt=new Date,l&&u?(t.Success=!0,t.NewValues=this.ConvertBackToMJFields(u)):(t.Success=!1,t.Message="Transaction failed")})),!0}else{const c=await this.ExecuteGQL(d,r);if(c&&c[o+e.EntityInfo.ClassName])return t.Success=!0,t.EndedAt=new Date,t.NewValues=this.ConvertBackToMJFields(c[o+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,y.LogError(r),null}}async Load(e,a,s=null,t){try{const r={};let o="",n="";for(let c=0;c<a.KeyValuePairs.length;c++){const u=e.Fields.find(h=>h.Name.trim().toLowerCase()===a.KeyValuePairs[c].FieldName.trim().toLowerCase()).EntityFieldInfo,l=a.GetValueByIndex(c),D=u.GraphQLType;if(n.length>0&&(n+=", "),n+=`$${u.CodeName}: ${D}!`,o.length>0&&(o+=", "),o+=`${u.CodeName}: $${u.CodeName}`,u.TSType===y.EntityFieldTSType.Number){if(isNaN(a.GetValueByIndex(c)))throw new Error(`Primary Key value ${l} (${u.Name}) is not a valid number`);r[u.CodeName]=parseInt(l)}else r[u.CodeName]=l}const i=s&&s.length>0?this.getRelatedEntityString(e.EntityInfo,s):"",p=new S,g=m.gql`query Single${e.EntityInfo.ClassName}${i.length>0?"Full":""} (${n}) {
|
|
132
|
+
${e.EntityInfo.ClassName}(${o}) {
|
|
131
133
|
${e.Fields.filter(c=>!c.EntityFieldInfo.IsBinaryFieldType).map(c=>c.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?c.CodeName.replace("__mj_","_mj__"):c.CodeName).join(`
|
|
132
134
|
`)}
|
|
133
135
|
${i}
|
|
134
136
|
}
|
|
135
137
|
}
|
|
136
|
-
`,
|
|
138
|
+
`,d=await this.ExecuteGQL(g,r);return d&&d[e.EntityInfo.ClassName]?this.ConvertBackToMJFields(d[e.EntityInfo.ClassName]):null}catch(r){return y.LogError(r),null}}ConvertBackToMJFields(e){return new S().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],o=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+=`
|
|
137
139
|
${n} {
|
|
138
|
-
${
|
|
140
|
+
${o.Fields.map(i=>i.CodeName).join(`
|
|
139
141
|
`)}
|
|
140
142
|
}
|
|
141
|
-
`}return s}async Delete(e,
|
|
142
|
-
`),
|
|
143
|
-
${
|
|
143
|
+
`}return s}async Delete(e,a,s){const t=new y.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),t.StartedAt=new Date,t.Type="delete",t.OriginalValues=e.Fields.map(u=>({FieldName:u.CodeName,Value:u.Value})),e.ResultHistory.push(t);const r={},o=[];let n="",i="",p="";for(let u of e.PrimaryKey.KeyValuePairs){const l=e.Fields.find(D=>D.Name.trim().toLowerCase()===u.FieldName.trim().toLowerCase());r[l.CodeName]=l.Value,o.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}!`,p.length>0&&(p+=`
|
|
144
|
+
`),p+=`${l.CodeName}`}o.push({varName:"options___",inputType:"DeleteOptionsInput!"}),r.options___=a||{SkipEntityAIActions:!1,SkipEntityActions:!1};const g="Delete"+e.EntityInfo.ClassName,d=m.gql`${g}(${n}, options___: $options___) {
|
|
145
|
+
${p}
|
|
144
146
|
}
|
|
145
|
-
`,c=
|
|
146
|
-
${
|
|
147
|
+
`,c=m.gql`mutation ${g} (${i}, $options___: DeleteOptionsInput!) {
|
|
148
|
+
${d}
|
|
147
149
|
}
|
|
148
|
-
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new
|
|
150
|
+
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new y.TransactionItem(e,"Delete",d,r,{mutationName:g,mutationInputTypes:o},(u,l)=>{if(t.EndedAt=new Date,l&&u){let D=!0;for(const h of e.PrimaryKey.KeyValuePairs)h.Value!==u[h.FieldName]&&(D=!1);D?t.Success=!0:(t.Success=!1,t.Message="Transaction failed to commit")}else t.Success=!1,t.Message="Transaction failed to commit"})),!0;{const u=await this.ExecuteGQL(c,r);if(u&&u[g]){const l=u[g];for(let D of e.PrimaryKey.KeyValuePairs){let h=l[D.FieldName],N=D.Value;if(typeof N=="number"&&(N=N.toString()),typeof h=="number"&&(h=h.toString()),N!==h)throw new Error(`Primary key value mismatch in server Delete response. Field: ${D.FieldName}, Original: ${N}, Returned: ${h}`)}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,y.LogError(r),!1}}async GetDatasetByName(e,a){const s=m.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
149
151
|
GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
150
152
|
DatasetID
|
|
151
153
|
DatasetName
|
|
@@ -154,7 +156,7 @@
|
|
|
154
156
|
LatestUpdateDate
|
|
155
157
|
Results
|
|
156
158
|
}
|
|
157
|
-
}`,t=await this.ExecuteGQL(s,{DatasetName:e,ItemFilters:
|
|
159
|
+
}`,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=m.gql`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
158
160
|
GetDatasetStatusByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
159
161
|
DatasetID
|
|
160
162
|
DatasetName
|
|
@@ -163,22 +165,22 @@
|
|
|
163
165
|
LatestUpdateDate
|
|
164
166
|
EntityUpdateDates
|
|
165
167
|
}
|
|
166
|
-
}`,t=await this.ExecuteGQL(s,{DatasetName:e,ItemFilters:
|
|
168
|
+
}`,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 C(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 o=m.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
|
|
167
169
|
GetRecordFavoriteStatus(params: $params) {
|
|
168
170
|
Success
|
|
169
171
|
IsFavorite
|
|
170
172
|
}
|
|
171
|
-
}`,n=await this.ExecuteGQL(
|
|
173
|
+
}`,n=await this.ExecuteGQL(o,{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 o=this.Entities.find(p=>p.Name===a);if(!o)throw new Error(`Entity ${a} not found in metadata`);const n=m.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
|
|
172
174
|
SetRecordFavoriteStatus(params: $params){
|
|
173
175
|
Success
|
|
174
176
|
}
|
|
175
|
-
}`,i=await this.ExecuteGQL(n,{params:{UserID:e,EntityID:
|
|
177
|
+
}`,i=await this.ExecuteGQL(n,{params:{UserID:e,EntityID:o.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=m.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
176
178
|
GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
|
|
177
179
|
Success
|
|
178
180
|
Status
|
|
179
181
|
RecordName
|
|
180
182
|
}
|
|
181
|
-
}`,t=await this.ExecuteGQL(s,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(
|
|
183
|
+
}`,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=m.gql`query GetEntityRecordNamesQuery ($info: [EntityRecordNameInput!]!) {
|
|
182
184
|
GetEntityRecordNames(info: $info) {
|
|
183
185
|
Success
|
|
184
186
|
Status
|
|
@@ -191,23 +193,35 @@
|
|
|
191
193
|
EntityName
|
|
192
194
|
RecordName
|
|
193
195
|
}
|
|
194
|
-
}`,s=await this.ExecuteGQL(
|
|
195
|
-
|
|
196
|
-
|
|
196
|
+
}`,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}async GetDataContextData(e){try{const a=m.gql`query GetDataContextData ($DataContextID: String!) {
|
|
197
|
+
GetDataContextData(DataContextID: $DataContextID) {
|
|
198
|
+
Success
|
|
199
|
+
ErrorMessages
|
|
200
|
+
Results
|
|
201
|
+
}
|
|
202
|
+
}`,s=await this.ExecuteGQL(a,{DataContextID:e});if(s&&s.GetDataContextData){if(s.GetDataContextData.Success)return s.GetDataContextData.Results.map(t=>JSON.parse(t));throw new Error(s.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(a){throw y.LogError(a),a}}async GetDataContextItemData(e){try{const a=m.gql`query GetDataContextItemData ($DataContextItemID: String!) {
|
|
203
|
+
GetDataContextItemData(DataContextItemID: $DataContextItemID) {
|
|
204
|
+
Success
|
|
205
|
+
ErrorMessage
|
|
206
|
+
Result
|
|
207
|
+
}
|
|
208
|
+
}`,s=await this.ExecuteGQL(a,{DataContextItemID:e});if(s&&s.GetDataContextItemData){if(s.GetDataContextItemData.Success)return JSON.parse(s.GetDataContextItemData.Result);throw new Error(s.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(a){throw y.LogError(a),a}}static async ExecuteGQL(e,a,s=!0){return E.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 y.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),t}else throw t;else throw y.LogError(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 E.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 m.GraphQLClient(e,{headers:r})}userInfoString(){return this.infoString(new y.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new y.UserRoleInfo(null))}infoString(e){let a="";const s=Object.keys(e);for(const t of s)t.startsWith("__mj_")?a+=t.replace("__mj_","_mj__")+`
|
|
209
|
+
`:t.startsWith("_")||(a+=t+`
|
|
210
|
+
`);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=ce.createClient({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=m.gql`subscription StatusUpdates($sessionId: String!) {
|
|
197
211
|
statusUpdates(sessionId: $sessionId) {
|
|
198
212
|
date
|
|
199
213
|
message
|
|
200
214
|
sessionId
|
|
201
215
|
}
|
|
202
216
|
}
|
|
203
|
-
`,t=new le.Observable(
|
|
217
|
+
`,t=new le.Observable(r=>(this._wsClient.subscribe({query:s,variables:{sessionId:e}},{next:o=>r.next(o.data.statusUpdates),error:o=>r.error(o),complete:()=>r.complete()}),()=>{console.log("would unsub here")}));return this._pushStatusRequests.push({sessionId:e,observable:t}),t}};f(E,"GraphQLDataProvider");let V=E;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 F=b;const de="MJ_Metadata",R="Metadata_KVPairs",J=class J extends F{constructor(){super(),this.dbPromise=ue.openDB(de,1,{upgrade(e){e.objectStoreNames.contains(R)||e.createObjectStore(R)}})}async setItem(e,a){const t=(await this.dbPromise).transaction(R,"readwrite");await t.objectStore(R).put(a,e),await t.done}async getItem(e){return await(await this.dbPromise).transaction(R).objectStore(R).get(e)}async remove(e){const s=(await this.dbPromise).transaction(R,"readwrite");await s.objectStore(R).delete(e),await s.done}};f(J,"BrowserIndexedDBStorageProvider");let T=J;async function me(w){const e=new V;return y.SetProvider(e),await e.Config(w),I.MJGlobal.Instance.RaiseEvent({event:I.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}f(me,"setupGraphQLClient");const j=class j{};f(j,"SyncRolesAndUsersResult");let $=j;const W=class W{};f(W,"RoleInput");let L=W;const z=class z{};f(z,"UserInput");let x=z;const H=class H{};f(H,"RolesAndUsersInput");let v=H;var ie=(w=>(w.Create="Create",w.Update="Update",w.CreateOrUpdate="CreateOrUpdate",w.Delete="Delete",w.DeleteWithFilter="DeleteWithFilter",w))(ie||{});const X=class X{};f(X,"ActionItemInput");let Q=X;const Z=class Z{constructor(){this.Results=[]}};f(Z,"SyncDataResult");let P=Z;const Y=class Y{};f(Y,"ActionItemOutput");let _=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 m.GraphQLClient(e,{headers:r})}async GetData(e,a){try{const t=await this.Client.request(`query GetData($input: GetDataInputType!) {
|
|
204
218
|
GetData(input: $input) {
|
|
205
219
|
Success
|
|
206
220
|
ErrorMessages
|
|
207
221
|
Queries
|
|
208
222
|
Results
|
|
209
223
|
}
|
|
210
|
-
}`,{input:{Queries:e,Token:"nope"}});return t&&t.GetData?{Success:t.GetData.Success,Results:t.GetData.Results.map(
|
|
224
|
+
}`,{input:{Queries:e,Token:"nope"}});return t&&t.GetData?{Success:t.GetData.Success,Results:t.GetData.Results.map(r=>r?I.SafeJSONParse(r):null),ErrorMessages:t.GetData.ErrorMessages,Queries:t.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:t.GetData?.ErrorMessages??["Unknown error"],Queries:t.GetData?.Queries??e}}catch(s){const t=`GraphQLSystemUserClient::GetData - Error getting geta - ${s}`;return y.LogError(t),{Success:!1,Results:[],ErrorMessages:[t],Queries:e}}}async GetAllRemoteEntities(){try{const a=await this.Client.request(`query GetAllEntities {
|
|
211
225
|
GetAllEntities {
|
|
212
226
|
Success
|
|
213
227
|
ErrorMessage
|
|
@@ -230,7 +244,7 @@
|
|
|
230
244
|
}
|
|
231
245
|
}
|
|
232
246
|
}
|
|
233
|
-
}`);return
|
|
247
|
+
}`);return a&&a.GetAllEntities?a.GetAllEntities:{Success:!1,Results:[],ErrorMessage:a.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return y.LogError(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const s=await this.Client.request(`mutation SyncData($items: [ActionItemInputType!]!) {
|
|
234
248
|
SyncData(items: $items) {
|
|
235
249
|
Success
|
|
236
250
|
Results {
|
|
@@ -254,9 +268,9 @@
|
|
|
254
268
|
RecordJSON
|
|
255
269
|
}
|
|
256
270
|
}
|
|
257
|
-
}`,{items:e});return s&&s.SyncData?s.SyncData:{Success:!1,Results:[]}}catch(
|
|
271
|
+
}`,{items:e});return s&&s.SyncData?s.SyncData:{Success:!1,Results:[]}}catch(a){return y.LogError(`GraphQLSystemUserClient::SyncData - Error syncing data - ${a}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const s=await this.Client.request(`mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {
|
|
258
272
|
SyncRolesAndUsers(data: $data) {
|
|
259
273
|
Success
|
|
260
274
|
}
|
|
261
|
-
}`,{data:e});return s&&s.SyncRolesAndUsers?s.SyncRolesAndUsers:{Success:!1}}catch(
|
|
275
|
+
}`,{data:e});return s&&s.SyncRolesAndUsers?s.SyncRolesAndUsers:{Success:!1}}catch(a){return y.LogError(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${a}`),{Success:!1}}}};f(ee,"GraphQLSystemUserClient");let q=ee;const te=class te{};f(te,"GetDataOutput");let M=te;const se=class se{};f(se,"SimpleRemoteEntityOutput");let U=se;const ae=class ae{};f(ae,"SimpleRemoteEntity");let A=ae;const re=class re{};f(re,"SimpleRemoteEntityField");let B=re;Object.defineProperty(exports,"gql",{enumerable:!0,get:function(){return m.gql}}),exports.ActionItemInput=Q,exports.ActionItemOutput=_,exports.FieldMapper=S,exports.GetDataOutput=M,exports.GraphQLDataProvider=V,exports.GraphQLProviderConfigData=G,exports.GraphQLSystemUserClient=q,exports.GraphQLTransactionGroup=C,exports.RoleInput=L,exports.RolesAndUsersInput=v,exports.SimpleRemoteEntity=A,exports.SimpleRemoteEntityField=B,exports.SimpleRemoteEntityOutput=U,exports.SyncDataAction=ie,exports.SyncDataResult=P,exports.SyncRolesAndUsersResult=$,exports.UserInput=x,exports.setupGraphQLClient=me;
|
|
262
276
|
//# sourceMappingURL=index.cjs.map
|