@memberjunction/graphql-dataprovider 2.29.2 → 2.30.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 +43 -41
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +41 -39
- 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 h=(N,e)=>oe(N,"name",{value:e,configurable:!0});var p=require("graphql-request"),y=require("@memberjunction/core"),ie=require("@memberjunction/core-entities"),ue=require("@tempfix/idb"),le=require("rxjs"),ce=require("graphql-ws"),ye=require("uuid"),I=require("@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 r in e)r in this._fieldMap&&(e[this._fieldMap[r]]=e[r],delete e[r]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([r,s])=>s===e)?.[0]??e}ReverseMapFields(e){const r=Object.fromEntries(Object.entries(this._fieldMap).map(([s,t])=>[t,s]));for(const s in e)s in r&&(e[r[s]]=e[s],delete e[s]);return e}};h(K,"FieldMapper");let S=K;const O=class O extends y.TransactionGroupBase{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=p.gql`
|
|
2
2
|
mutation ExecuteTransactionGroup($group: TransactionInputType!) {
|
|
3
3
|
ExecuteTransactionGroup(group: $group) {
|
|
4
4
|
Success
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
ResultsJSON
|
|
7
7
|
}
|
|
8
8
|
}
|
|
9
|
-
`,r=[];for(const a of this.PendingTransactions)r.push({EntityName:a.BaseEntity.EntityInfo.Name,EntityObjectJSON:await a.BaseEntity.GetDataObjectJSON(),OperationType:a.OperationType});const s={group:{Items:r,Variables:this.Variables.map(a=>({Name:a.Name,ItemIndex:this.MapVariableEntityObjectToPosition(a),FieldName:a.FieldName,Type:a.Type}))}},t=await this._provider.ExecuteGQL(e,s);if(t&&t.ExecuteTransactionGroup){const a=t.ExecuteTransactionGroup,
|
|
9
|
+
`,r=[];for(const a of this.PendingTransactions)r.push({EntityName:a.BaseEntity.EntityInfo.Name,EntityObjectJSON:await a.BaseEntity.GetDataObjectJSON(),OperationType:a.OperationType});const s={group:{Items:r,Variables:this.Variables.map(a=>({Name:a.Name,ItemIndex:this.MapVariableEntityObjectToPosition(a),FieldName:a.FieldName,Type:a.Type}))}},t=await this._provider.ExecuteGQL(e,s);if(t&&t.ExecuteTransactionGroup){const a=t.ExecuteTransactionGroup,o=[];for(let i=0;i<this.PendingTransactions.length;i++){const n=a.ResultsJSON[i],f=I.SafeJSONParse(n),g=this.PendingTransactions[i];o.push(new y.TransactionResult(g,f,f!==null))}return o}else throw new Error("Failed to execute transaction group")}};h(O,"GraphQLTransactionGroup");let C=O;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,r,s,t,a,o,i,n){super({Token:e,URL:r,WSURL:s,MJAPIKey:n,RefreshTokenFunction:t},a,o,i)}};h(k,"GraphQLProviderConfigData");let F=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()}
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
}
|
|
15
15
|
`,this._currentUserQuery=p.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,r){try{const s=this.GenerateUUID();return r?(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 r=this.ConvertBackToMJFields(e.CurrentUser),s=r.UserRoles_UserIDArray.map(t=>this.ConvertBackToMJFields(t));return r.UserRoles_UserIDArray=s,new y.UserInfo(this,{...r,UserRoles:s})}}async RunReport(e,r){const s=p.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,r){if(e.QueryID)return this.RunQueryByID(e.QueryID,r);if(e.QueryName)return this.RunQueryByName(e.QueryName,r);throw new Error("No QueryID or QueryName provided to RunQuery")}async RunQueryByID(e,r){const
|
|
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,r){if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryName,r);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryName,r);throw new Error("No QueryID or QueryName provided to RunQuery")}async RunQueryByID(e,r,s,t){const a=p.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};r!==void 0&&(o.CategoryID=r),s!==void 0&&(o.CategoryName=s);const i=await this.ExecuteGQL(a,o);if(i&&i.GetQueryData)return this.TransformQueryPayload(i.GetQueryData)}async RunQueryByName(e,r,s,t){const a=p.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:r,CategoryName:s},i=await this.ExecuteGQL(a,o);if(i&&i.GetQueryDataByName)return this.TransformQueryPayload(i.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(r){return
|
|
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(r){return y.LogError(`Error transforming query payload: ${r}`),null}}async RunView(e,r){try{let s="",t="";if(e){const a={};let o,i;if(e.ViewEntity)i=e.ViewEntity,o=i.Entity;else{const{entityName:u,v:l}=await this.getEntityNameAndUserView(e,r);i=l,o=u}const n=this.Entities.find(u=>u.Name===o);if(!n)throw new Error(`Entity ${o} not found in metadata`);let f=!1;e.ViewID?(s=`Run${n.ClassName}ViewByID`,t="RunViewByIDInput",a.ViewID=e.ViewID):e.ViewName?(s=`Run${n.ClassName}ViewByName`,t="RunViewByNameInput",a.ViewName=e.ViewName):(f=!0,s=`Run${n.ClassName}DynamicView`,t="RunDynamicViewInput",a.EntityName=e.EntityName),a.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",a.OrderBy=e.OrderBy?e.OrderBy:"",a.UserSearchString=e.UserSearchString?e.UserSearchString:"",a.Fields=e.Fields,a.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,a.MaxRows=e.MaxRows?e.MaxRows:0,a.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,a.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(a.AuditLogDescription=e.AuditLogDescription),f||(a.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",a.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,a.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",a.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1);const g=this.getViewRunTimeFieldList(n,i,e,f),d=p.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:a});if(c&&c[s]){const u=c[s].Results;if(u&&u.length>0){const l=n.Fields.filter(m=>m.CodeName!==m.Name&&m.CodeName!==void 0);u.forEach(m=>{this.ConvertBackToMJFields(m),l.forEach(D=>{m[D.Name]=m[D.CodeName]})})}return c[s]}}else throw"No parameters passed to RunView";return null}catch(s){throw y.LogError(s),s}}async RunViews(e,r){try{let s=[],t=[],a=[];for(const n of e){let f="",g="";const d={};let c=null,u=null;if(n.ViewEntity)u=n.ViewEntity,c=u.Get("Entity");else{const{entityName:D,v:w}=await this.getEntityNameAndUserView(n,r);u=w,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 m=!1;n.ViewID?(f=`Run${l.ClassName}ViewByID`,g="RunViewByIDInput",d.ViewID=n.ViewID):n.ViewName?(f=`Run${l.ClassName}ViewByName`,g="RunViewByNameInput",d.ViewName=n.ViewName):(m=!0,f=`Run${l.ClassName}DynamicView`,g="RunDynamicViewInput",d.EntityName=n.EntityName),d.ExtraFilter=n.ExtraFilter||"",d.OrderBy=n.OrderBy||"",d.UserSearchString=n.UserSearchString||"",d.Fields=n.Fields,d.IgnoreMaxRows=n.IgnoreMaxRows||!1,d.MaxRows=n.MaxRows||0,d.ForceAuditLog=n.ForceAuditLog||!1,d.ResultType=n.ResultType||"simple",n.AuditLogDescription&&n.AuditLogDescription.length>0&&(d.AuditLogDescription=n.AuditLogDescription),m||(d.ExcludeUserViewRunID=n.ExcludeUserViewRunID||"",d.ExcludeDataFromAllPriorViewRuns=n.ExcludeDataFromAllPriorViewRuns||!1,d.OverrideExcludeFilter=n.OverrideExcludeFilter||"",d.SaveViewResults=n.SaveViewResults||!1),s.push(d),a.push(...this.getViewRunTimeFieldList(l,u,n,m))}const o=p.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
|
-
}`,
|
|
74
|
+
}`,i=await this.ExecuteGQL(o,{input:s});if(i&&i.RunViews){const n=i.RunViews;for(const[f,g]of n.entries())g.Results=g.Results.map(d=>{let c=JSON.parse(d.Data);return this.ConvertBackToMJFields(c),c});return n}return null}catch(s){throw y.LogError(s),s}}async getEntityNameAndUserView(e,r){let s,t;if(e.EntityName)s=e.EntityName;else if(e.ViewID)t=await ie.ViewInfo.GetViewEntity(e.ViewID,r),s=t.Entity;else if(e.ViewName)t=await ie.ViewInfo.GetViewEntityByName(e.ViewName,r),s=t.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:s,v:t}}getViewRunTimeFieldList(e,r,s,t){const a=[],o=new S;if(s.Fields){for(const i of e.PrimaryKeys)s.Fields.find(n=>n.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);s.Fields.forEach(i=>{a.push(o.MapFieldName(i))})}else if(t)e.Fields.forEach(i=>{i.IsBinaryFieldType||a.push(o.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)a.find(n=>n.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);r.Columns.forEach(i=>{i.hidden===!1&&!a.find(n=>n.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&a.push(o.MapFieldName(i.EntityField.CodeName))})}return a}get ProviderType(){return y.ProviderType.Network}async GetRecordChanges(e,r){try{const s={EntityName:"Record Changes",ExtraFilter:`RecordID = '${r.Values()}' AND Entity = '${e}'`},t=await this.RunView(s);return t?t.Results.sort((a,o)=>a.ChangedAt>o.ChangedAt?-1:1):null}catch(s){throw y.LogError(s),s}}async GetRecordDependencies(e,r){try{const s=p.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(r.KeyValuePairs)}};return(await this.ExecuteGQL(s,t))?.GetRecordDependencies}catch(s){throw
|
|
86
|
+
}`,t={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}};return(await this.ExecuteGQL(s,t))?.GetRecordDependencies}catch(s){throw y.LogError(s),s}}ensureKeyValuePairValueIsString(e){return e.map(r=>({FieldName:r.FieldName,Value:r.Value.toString()}))}async GetRecordDuplicates(e,r){if(!e)return null;const s=p.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 a=await this.ExecuteGQL(s,{params:t});if(a&&a.GetRecordDuplicates)return a.GetRecordDuplicates}async MergeRecords(e){const r=this.Entities.find(s=>s.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!r||!r.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const s=p.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(
|
|
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,r,s){const t=new y.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const a={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 i=`${o}${e.EntityInfo.ClassName}`,n=e.Fields.filter(c=>!c.ReadOnly||c.IsPrimaryKey&&e.IsSaved),f=new S,g=` ${i}(input: $input) {
|
|
124
126
|
${e.Fields.map(c=>f.MapFieldName(c.CodeName)).join(`
|
|
125
127
|
`)}
|
|
126
|
-
}`,
|
|
127
|
-
${
|
|
128
|
+
}`,d=p.gql`mutation ${o}${e.EntityInfo.ClassName} ($input: ${i}Input!) {
|
|
129
|
+
${g}
|
|
128
130
|
}
|
|
129
|
-
`;for(let c=0;c<
|
|
130
|
-
${e.EntityInfo.ClassName}(${
|
|
131
|
+
`;for(let c=0;c<n.length;c++){const u=n[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 m=Number(l);isNaN(m)||(l=m)}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=""),a.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})}),a.input.OldValues___=c}if(e.TransactionGroup){const c=[{varName:"input",inputType:i+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new y.TransactionItem(e,t.Type==="create"?"Create":"Update",g,a,{mutationName:i,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,a);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(a){return t.Success=!1,t.EndedAt=new Date,t.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,y.LogError(a),null}}async Load(e,r,s=null,t){try{const a={};let o="",i="";for(let c=0;c<r.KeyValuePairs.length;c++){const u=e.Fields.find(D=>D.Name.trim().toLowerCase()===r.KeyValuePairs[c].FieldName.trim().toLowerCase()).EntityFieldInfo,l=r.GetValueByIndex(c),m=u.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${u.CodeName}: ${m}!`,o.length>0&&(o+=", "),o+=`${u.CodeName}: $${u.CodeName}`,u.TSType===y.EntityFieldTSType.Number){if(isNaN(r.GetValueByIndex(c)))throw new Error(`Primary Key value ${l} (${u.Name}) is not a valid number`);a[u.CodeName]=parseInt(l)}else a[u.CodeName]=l}const n=s&&s.length>0?this.getRelatedEntityString(e.EntityInfo,s):"",f=new S,g=p.gql`query Single${e.EntityInfo.ClassName}${n.length>0?"Full":""} (${i}) {
|
|
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
|
+
${n}
|
|
134
136
|
}
|
|
135
137
|
}
|
|
136
|
-
`,
|
|
137
|
-
${
|
|
138
|
-
${
|
|
138
|
+
`,d=await this.ExecuteGQL(g,a);return d&&d[e.EntityInfo.ClassName]?this.ConvertBackToMJFields(d[e.EntityInfo.ClassName]):null}catch(a){return y.LogError(a),null}}ConvertBackToMJFields(e){return new S().ReverseMapFields(e),e}getRelatedEntityString(e,r){let s="";for(let t=0;t<e.RelatedEntities.length;t++)if(r.indexOf(e.RelatedEntities[t].RelatedEntity)>=0){const a=e.RelatedEntities[t],o=this.Entities.find(n=>n.ID===a.RelatedEntityID);let i="";a.Type.toLowerCase().trim()==="many to many"?i=`${a.RelatedEntityCodeName}_${a.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${a.RelatedEntityCodeName}_${a.RelatedEntityJoinField.replace(/\s/g,"")}`,s+=`
|
|
139
|
+
${i} {
|
|
140
|
+
${o.Fields.map(n=>n.CodeName).join(`
|
|
139
141
|
`)}
|
|
140
142
|
}
|
|
141
|
-
`}return s}async Delete(e,r,s){const t=new
|
|
142
|
-
`),f+=`${l.CodeName}`}
|
|
143
|
+
`}return s}async Delete(e,r,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 a={},o=[];let i="",n="",f="";for(let u of e.PrimaryKey.KeyValuePairs){const l=e.Fields.find(m=>m.Name.trim().toLowerCase()===u.FieldName.trim().toLowerCase());a[l.CodeName]=l.Value,o.push({varName:l.CodeName,inputType:l.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${l.CodeName}: $${l.CodeName}`,n.length>0&&(n+=", "),n+=`$${l.CodeName}: ${l.EntityFieldInfo.GraphQLType}!`,f.length>0&&(f+=`
|
|
144
|
+
`),f+=`${l.CodeName}`}o.push({varName:"options___",inputType:"DeleteOptionsInput!"}),a.options___=r||{SkipEntityAIActions:!1,SkipEntityActions:!1};const g="Delete"+e.EntityInfo.ClassName,d=p.gql`${g}(${i}, options___: $options___) {
|
|
143
145
|
${f}
|
|
144
146
|
}
|
|
145
|
-
`,c=p.gql`mutation ${
|
|
146
|
-
${
|
|
147
|
+
`,c=p.gql`mutation ${g} (${n}, $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,a,{mutationName:g,mutationInputTypes:o},(u,l)=>{if(t.EndedAt=new Date,l&&u){let m=!0;for(const D of e.PrimaryKey.KeyValuePairs)D.Value!==u[D.FieldName]&&(m=!1);m?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,a);if(u&&u[g]){const l=u[g];for(let m of e.PrimaryKey.KeyValuePairs){let D=l[m.FieldName],w=m.Value;if(typeof w=="number"&&(w=w.toString()),typeof D=="number"&&(D=D.toString()),w!==D)throw new Error(`Primary key value mismatch in server Delete response. Field: ${m.FieldName}, Original: ${w}, 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(a){return t.EndedAt=new Date,t.Success=!1,t.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,y.LogError(a),!1}}async GetDatasetByName(e,r){const s=p.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
149
151
|
GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
150
152
|
DatasetID
|
|
151
153
|
DatasetName
|
|
@@ -163,16 +165,16 @@
|
|
|
163
165
|
LatestUpdateDate
|
|
164
166
|
EntityUpdateDates
|
|
165
167
|
}
|
|
166
|
-
}`,t=await this.ExecuteGQL(s,{DatasetName:e,ItemFilters:r});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
|
|
168
|
+
}`,t=await this.ExecuteGQL(s,{DatasetName:e,ItemFilters:r});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,r,s){if(!s.Validate().IsValid)return!1;const a=this.Entities.find(n=>n.Name===r);if(!a)throw new Error(`Entity ${r} not found in metadata`);const o=p.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
|
|
167
169
|
GetRecordFavoriteStatus(params: $params) {
|
|
168
170
|
Success
|
|
169
171
|
IsFavorite
|
|
170
172
|
}
|
|
171
|
-
}`,
|
|
173
|
+
}`,i=await this.ExecuteGQL(o,{params:{UserID:e,EntityID:a.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,r,s,t,a){const o=this.Entities.find(f=>f.Name===r);if(!o)throw new Error(`Entity ${r} not found in metadata`);const i=p.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
|
|
172
174
|
SetRecordFavoriteStatus(params: $params){
|
|
173
175
|
Success
|
|
174
176
|
}
|
|
175
|
-
}`,
|
|
177
|
+
}`,n=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:o.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.KeyValuePairs)},IsFavorite:t}});if(n&&n.SetRecordFavoriteStatus!==null)return n.SetRecordFavoriteStatus.Success}async GetEntityRecordName(e,r){if(!e||!r||r.KeyValuePairs?.length===0)return null;const s=p.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
176
178
|
GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
|
|
177
179
|
Success
|
|
178
180
|
Status
|
|
@@ -191,7 +193,7 @@
|
|
|
191
193
|
EntityName
|
|
192
194
|
RecordName
|
|
193
195
|
}
|
|
194
|
-
}`,s=await this.ExecuteGQL(r,{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,r,s=!0){return
|
|
196
|
+
}`,s=await this.ExecuteGQL(r,{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,r,s=!0){return E.Instance.ExecuteGQL(e,r,s)}async ExecuteGQL(e,r,s=!0){try{return await this._client.request(e,r)}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,r,!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,r,s,t){const a={"x-session-id":s};return r&&(a.authorization="Bearer "+r),t&&(a["x-mj-api-key"]=t),new p.GraphQLClient(e,{headers:a})}userInfoString(){return this.infoString(new y.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new y.UserRoleInfo(null))}infoString(e){let r="";const s=Object.keys(e);for(const t of s)t.startsWith("__mj_")?r+=t.replace("__mj_","_mj__")+`
|
|
195
197
|
`:t.startsWith("_")||(r+=t+`
|
|
196
198
|
`);return r}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new G),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 r=this._pushStatusRequests.find(a=>a.sessionId===e);if(r)return r.observable;const s=p.gql`subscription StatusUpdates($sessionId: String!) {
|
|
197
199
|
statusUpdates(sessionId: $sessionId) {
|
|
@@ -200,14 +202,14 @@
|
|
|
200
202
|
sessionId
|
|
201
203
|
}
|
|
202
204
|
}
|
|
203
|
-
`,t=new le.Observable(a=>(this._wsClient.subscribe({query:s,variables:{sessionId:e}},{next:
|
|
205
|
+
`,t=new le.Observable(a=>(this._wsClient.subscribe({query:s,variables:{sessionId:e}},{next:o=>a.next(o.data.statusUpdates),error:o=>a.error(o),complete:()=>a.complete()}),()=>{console.log("would unsub here")}));return this._pushStatusRequests.push({sessionId:e,observable:t}),t}};h(E,"GraphQLDataProvider");let V=E;const b=class b{constructor(){this._localStorage={}}async getItem(e){return new Promise(r=>{this._localStorage.hasOwnProperty(e)?r(this._localStorage[e]):r(null)})}async setItem(e,r){return new Promise(s=>{this._localStorage[e]=r,s()})}async remove(e){return new Promise(r=>{this._localStorage.hasOwnProperty(e)&&delete this._localStorage[e],r()})}};h(b,"BrowserStorageProviderBase");let T=b;const de="MJ_Metadata",R="Metadata_KVPairs",J=class J extends T{constructor(){super(),this.dbPromise=ue.openDB(de,1,{upgrade(e){e.objectStoreNames.contains(R)||e.createObjectStore(R)}})}async setItem(e,r){const t=(await this.dbPromise).transaction(R,"readwrite");await t.objectStore(R).put(r,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}};h(J,"BrowserIndexedDBStorageProvider");let G=J;async function me(N){const e=new V;return y.SetProvider(e),await e.Config(N),I.MJGlobal.Instance.RaiseEvent({event:I.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}h(me,"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 v=z;const H=class H{};h(H,"RolesAndUsersInput");let P=H;var ne=(N=>(N.Create="Create",N.Update="Update",N.CreateOrUpdate="CreateOrUpdate",N.Delete="Delete",N.DeleteWithFilter="DeleteWithFilter",N))(ne||{});const X=class X{};h(X,"ActionItemInput");let _=X;const Z=class Z{constructor(){this.Results=[]}};h(Z,"SyncDataResult");let Q=Z;const Y=class Y{};h(Y,"ActionItemOutput");let U=Y;const ee=class ee{get Client(){return this._client}constructor(e,r,s,t){const a={"x-session-id":s};r&&(a.authorization="Bearer "+r),t&&(a["x-mj-api-key"]=t),this._client=new p.GraphQLClient(e,{headers:a})}async GetData(e,r){try{const t=await this.Client.request(`query GetData($input: GetDataInputType!) {
|
|
204
206
|
GetData(input: $input) {
|
|
205
207
|
Success
|
|
206
208
|
ErrorMessages
|
|
207
209
|
Queries
|
|
208
210
|
Results
|
|
209
211
|
}
|
|
210
|
-
}`,{input:{Queries:e,Token:"nope"}});return t&&t.GetData?{Success:t.GetData.Success,Results:t.GetData.Results.map(a=>a?I.SafeJSONParse(a):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
|
|
212
|
+
}`,{input:{Queries:e,Token:"nope"}});return t&&t.GetData?{Success:t.GetData.Success,Results:t.GetData.Results.map(a=>a?I.SafeJSONParse(a):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 r=await this.Client.request(`query GetAllEntities {
|
|
211
213
|
GetAllEntities {
|
|
212
214
|
Success
|
|
213
215
|
ErrorMessage
|
|
@@ -230,7 +232,7 @@
|
|
|
230
232
|
}
|
|
231
233
|
}
|
|
232
234
|
}
|
|
233
|
-
}`);return r&&r.GetAllEntities?r.GetAllEntities:{Success:!1,Results:[],ErrorMessage:r.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return
|
|
235
|
+
}`);return r&&r.GetAllEntities?r.GetAllEntities:{Success:!1,Results:[],ErrorMessage:r.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
236
|
SyncData(items: $items) {
|
|
235
237
|
Success
|
|
236
238
|
Results {
|
|
@@ -254,9 +256,9 @@
|
|
|
254
256
|
RecordJSON
|
|
255
257
|
}
|
|
256
258
|
}
|
|
257
|
-
}`,{items:e});return s&&s.SyncData?s.SyncData:{Success:!1,Results:[]}}catch(r){return
|
|
259
|
+
}`,{items:e});return s&&s.SyncData?s.SyncData:{Success:!1,Results:[]}}catch(r){return y.LogError(`GraphQLSystemUserClient::SyncData - Error syncing data - ${r}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const s=await this.Client.request(`mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {
|
|
258
260
|
SyncRolesAndUsers(data: $data) {
|
|
259
261
|
Success
|
|
260
262
|
}
|
|
261
|
-
}`,{data:e});return s&&s.SyncRolesAndUsers?s.SyncRolesAndUsers:{Success:!1}}catch(r){return
|
|
263
|
+
}`,{data:e});return s&&s.SyncRolesAndUsers?s.SyncRolesAndUsers:{Success:!1}}catch(r){return y.LogError(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${r}`),{Success:!1}}}};h(ee,"GraphQLSystemUserClient");let M=ee;const te=class te{};h(te,"GetDataOutput");let x=te;const se=class se{};h(se,"SimpleRemoteEntityOutput");let q=se;const re=class re{};h(re,"SimpleRemoteEntity");let A=re;const ae=class ae{};h(ae,"SimpleRemoteEntityField");let B=ae;Object.defineProperty(exports,"gql",{enumerable:!0,get:function(){return p.gql}}),exports.ActionItemInput=_,exports.ActionItemOutput=U,exports.FieldMapper=S,exports.GetDataOutput=x,exports.GraphQLDataProvider=V,exports.GraphQLProviderConfigData=F,exports.GraphQLSystemUserClient=M,exports.GraphQLTransactionGroup=C,exports.RoleInput=L,exports.RolesAndUsersInput=P,exports.SimpleRemoteEntity=A,exports.SimpleRemoteEntityField=B,exports.SimpleRemoteEntityOutput=q,exports.SyncDataAction=ne,exports.SyncDataResult=Q,exports.SyncRolesAndUsersResult=$,exports.UserInput=v,exports.setupGraphQLClient=me;
|
|
262
264
|
//# sourceMappingURL=index.cjs.map
|