@memberjunction/graphql-dataprovider 2.13.0 → 2.13.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +24 -24
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +20 -20
- 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 _=Object.defineProperty;var g=(I,e)=>_(I,"name",{value:e,configurable:!0});var R=require("graphql-request"),
|
|
1
|
+
"use strict";var _=Object.defineProperty;var g=(I,e)=>_(I,"name",{value:e,configurable:!0});var R=require("graphql-request"),y=require("@memberjunction/core"),U=require("@memberjunction/core-entities"),q=require("@tempfix/idb"),Q=require("rxjs"),B=require("graphql-ws"),M=require("@memberjunction/global");const $=class ${constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const s in e)s in this._fieldMap&&(e[this._fieldMap[s]]=e[s],delete e[s]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([s,a])=>a===e)?.[0]??e}ReverseMapFields(e){const s=Object.fromEntries(Object.entries(this._fieldMap).map(([a,t])=>[t,a]));for(const a in e)a in s&&(e[s[a]]=e[a],delete e[a]);return e}};g($,"FieldMapper");let h=$;const x=class x extends y.ProviderConfigDataBase{get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,s,a,t,r,c,i){super({Token:e,URL:s,WSURL:a,RefreshTokenFunction:t},r,c,i)}};g(x,"GraphQLProviderConfigData");let V=x;const d=class d extends y.ProviderBase{constructor(){super(...arguments),this._innerCurrentUserQueryString=`CurrentUser {
|
|
2
2
|
${this.userInfoString()}
|
|
3
3
|
UserRoles_UserIDArray {
|
|
4
4
|
${this.userRoleInfoString()}
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
}
|
|
7
7
|
`,this._currentUserQuery=R.gql`query CurrentUserAndRoles {
|
|
8
8
|
${this._innerCurrentUserQueryString}
|
|
9
|
-
}`,this._wsClient=null,this._pushStatusRequests=[]}get ConfigData(){return d._configData}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}GenerateUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var s=Math.random()*16|0,a=e==="x"?s:s&3|8;return a.toString(16)})}async Config(e){try{return d._sessionId===void 0&&(d._sessionId=this.GenerateUUID()),d._configData=e,d._client||(d._client=d.CreateNewGraphQLClient(e.URL,e.Token,d._sessionId)),super.Config(e)}catch(s){throw
|
|
9
|
+
}`,this._wsClient=null,this._pushStatusRequests=[]}get ConfigData(){return d._configData}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}GenerateUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var s=Math.random()*16|0,a=e==="x"?s:s&3|8;return a.toString(16)})}async Config(e){try{return d._sessionId===void 0&&(d._sessionId=this.GenerateUUID()),d._configData=e,d._client||(d._client=d.CreateNewGraphQLClient(e.URL,e.Token,d._sessionId)),super.Config(e)}catch(s){throw y.LogError(s),s}}get sessionId(){return d._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await d.ExecuteGQL(this._currentUserQuery,null);if(e){const s=this.ConvertBackToMJFields(e.CurrentUser),a=s.UserRoles_UserIDArray.map(t=>this.ConvertBackToMJFields(t));return s.UserRoles_UserIDArray=a,new y.UserInfo(this,{...s,UserRoles:a})}}async RunReport(e,s){const a=R.gql`
|
|
10
10
|
query GetReportDataQuery ($ReportID: String!) {
|
|
11
11
|
GetReportData(ReportID: $ReportID) {
|
|
12
12
|
Success
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
ExecutionTime
|
|
25
25
|
ErrorMessage
|
|
26
26
|
}
|
|
27
|
-
}`,t=await d.ExecuteGQL(a,{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,s){try{let a="",t="";if(e){const r={};let
|
|
27
|
+
}`,t=await d.ExecuteGQL(a,{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,s){try{let a="",t="";if(e){const r={};let c,i;if(e.ViewEntity)i=e.ViewEntity,c=i.Entity;else{const{entityName:o,v:l}=await this.getEntityNameAndUserView(e,s);i=l,c=o}const n=this.Entities.find(o=>o.Name===c);if(!n)throw new Error(`Entity ${c} not found in metadata`);let f=!1;e.ViewID?(a=`Run${n.ClassName}ViewByID`,t="RunViewByIDInput",r.ViewID=e.ViewID):e.ViewName?(a=`Run${n.ClassName}ViewByName`,t="RunViewByNameInput",r.ViewName=e.ViewName):(f=!0,a=`Run${n.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),f||(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 w=this.getViewRunTimeFieldList(n,i,e,f),m=R.gql`
|
|
28
28
|
query RunViewQuery ($input: ${t}!) {
|
|
29
29
|
${a}(input: $input) {
|
|
30
30
|
Results {
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
Success
|
|
39
39
|
ErrorMessage
|
|
40
40
|
}
|
|
41
|
-
}`,u=await d.ExecuteGQL(
|
|
41
|
+
}`,u=await d.ExecuteGQL(m,{input:r});if(u&&u[a]){const o=u[a].Results;if(o&&o.length>0){const l=n.Fields.filter(p=>p.CodeName!==p.Name&&p.CodeName!==void 0);o.forEach(p=>{this.ConvertBackToMJFields(p),l.forEach(D=>{p[D.Name]=p[D.CodeName]})})}return u[a]}}else throw"No parameters passed to RunView";return null}catch(a){throw y.LogError(a),a}}async RunViews(e,s){try{let a=[],t=[],r=[];for(const n of e){let f="",w="";const m={};let u=null,o=null;if(n.ViewEntity)o=n.ViewEntity,u=o.Get("Entity");else{const{entityName:D,v:E}=await this.getEntityNameAndUserView(n,s);o=E,u=D}const l=this.Entities.find(D=>D.Name===u);if(!l)throw new Error(`Entity ${u} not found in metadata`);t.push(l);let p=!1;n.ViewID?(f=`Run${l.ClassName}ViewByID`,w="RunViewByIDInput",m.ViewID=n.ViewID):n.ViewName?(f=`Run${l.ClassName}ViewByName`,w="RunViewByNameInput",m.ViewName=n.ViewName):(p=!0,f=`Run${l.ClassName}DynamicView`,w="RunDynamicViewInput",m.EntityName=n.EntityName),m.ExtraFilter=n.ExtraFilter||"",m.OrderBy=n.OrderBy||"",m.UserSearchString=n.UserSearchString||"",m.Fields=n.Fields,m.IgnoreMaxRows=n.IgnoreMaxRows||!1,m.MaxRows=n.MaxRows||0,m.ForceAuditLog=n.ForceAuditLog||!1,m.ResultType=n.ResultType||"simple",n.AuditLogDescription&&n.AuditLogDescription.length>0&&(m.AuditLogDescription=n.AuditLogDescription),p||(m.ExcludeUserViewRunID=n.ExcludeUserViewRunID||"",m.ExcludeDataFromAllPriorViewRuns=n.ExcludeDataFromAllPriorViewRuns||!1,m.OverrideExcludeFilter=n.OverrideExcludeFilter||"",m.SaveViewResults=n.SaveViewResults||!1),a.push(m),r.push(...this.getViewRunTimeFieldList(l,o,n,p))}const c=R.gql`
|
|
42
42
|
query RunViewsQuery ($input: [RunViewGenericInput!]!) {
|
|
43
43
|
RunViews(input: $input) {
|
|
44
44
|
Results {
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
Success
|
|
54
54
|
ErrorMessage
|
|
55
55
|
}
|
|
56
|
-
}`,i=await d.ExecuteGQL(
|
|
56
|
+
}`,i=await d.ExecuteGQL(c,{input:a});if(i&&i.RunViews){const n=i.RunViews;for(const[f,w]of n.entries())w.Results=w.Results.map(m=>{let u=JSON.parse(m.Data);return this.ConvertBackToMJFields(u),u});return n}return null}catch(a){throw y.LogError(a),a}}async getEntityNameAndUserView(e,s){let a,t;if(e.EntityName)a=e.EntityName;else if(e.ViewID)t=await U.ViewInfo.GetViewEntity(e.ViewID,s),a=t.Entity;else if(e.ViewName)t=await U.ViewInfo.GetViewEntityByName(e.ViewName,s),a=t.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:a,v:t}}getViewRunTimeFieldList(e,s,a,t){const r=[],c=new h;if(a.Fields){for(const i of e.PrimaryKeys)a.Fields.find(n=>n.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&r.push(i.Name);a.Fields.forEach(i=>{r.push(c.MapFieldName(i))})}else if(t)e.Fields.forEach(i=>{i.IsBinaryFieldType||r.push(c.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)r.find(n=>n.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&r.push(i.Name);s.Columns.forEach(i=>{i.hidden===!1&&!r.find(n=>n.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&r.push(c.MapFieldName(i.EntityField.CodeName))})}return r}get ProviderType(){return y.ProviderType.Network}async GetRecordChanges(e,s){try{const a={EntityName:"Record Changes",ExtraFilter:`RecordID = '${s.Values()}' AND Entity = '${e}'`},t=await this.RunView(a);return t?t.Results.sort((r,c)=>r.ChangedAt>c.ChangedAt?-1:1):null}catch(a){throw y.LogError(a),a}}async GetRecordDependencies(e,s){try{const a=R.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
57
57
|
GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
|
|
58
58
|
EntityName
|
|
59
59
|
RelatedEntityName
|
|
@@ -65,7 +65,7 @@
|
|
|
65
65
|
}
|
|
66
66
|
}
|
|
67
67
|
}
|
|
68
|
-
}`,t={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.KeyValuePairs)}};return(await d.ExecuteGQL(a,t))?.GetRecordDependencies}catch(a){throw
|
|
68
|
+
}`,t={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.KeyValuePairs)}};return(await d.ExecuteGQL(a,t))?.GetRecordDependencies}catch(a){throw y.LogError(a),a}}ensureKeyValuePairValueIsString(e){return e.map(s=>({FieldName:s.FieldName,Value:s.Value.toString()}))}async GetRecordDuplicates(e,s){if(!e)return null;const a=R.gql`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
|
|
69
69
|
GetRecordDuplicates(params: $params) {
|
|
70
70
|
Status
|
|
71
71
|
ErrorMessage
|
|
@@ -87,7 +87,7 @@
|
|
|
87
87
|
}
|
|
88
88
|
}
|
|
89
89
|
}
|
|
90
|
-
}`;let t={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(
|
|
90
|
+
}`;let t={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(c=>c.Copy())};const r=await d.ExecuteGQL(a,{params:t});if(r&&r.GetRecordDuplicates)return r.GetRecordDuplicates}async MergeRecords(e){const s=this.Entities.find(a=>a.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!s||!s.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const a=R.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
|
|
91
91
|
MergeRecords(request: $request) {
|
|
92
92
|
Success
|
|
93
93
|
OverallStatus
|
|
@@ -104,32 +104,32 @@
|
|
|
104
104
|
Message
|
|
105
105
|
}
|
|
106
106
|
}
|
|
107
|
-
}`,t={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(
|
|
107
|
+
}`,t={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(c=>({FieldName:c.FieldName,Value:c.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(c=>c.Copy())};return(await d.ExecuteGQL(a,{request:t}))?.MergeRecords}catch(a){return y.LogError(a),{Success:!1,OverallStatus:a&&a.message?a.message:a,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,s,a){const t=new y.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const r={input:{}},c=e.IsSaved?"Update":"Create";t.StartedAt=new Date,t.Type=e.IsSaved?"update":"create",t.OriginalValues=e.Fields.map(u=>({FieldName:u.CodeName,Value:u.Value})),e.ResultHistory.push(t);const i=`${c}${e.EntityInfo.ClassName}`,n=e.Fields.filter(u=>!u.ReadOnly||u.IsPrimaryKey&&e.IsSaved),f=new h,w=` ${i}(input: $input) {
|
|
108
108
|
${e.Fields.map(u=>f.MapFieldName(u.CodeName)).join(`
|
|
109
109
|
`)}
|
|
110
|
-
}`,
|
|
110
|
+
}`,m=R.gql`mutation ${c}${e.EntityInfo.ClassName} ($input: ${i}Input!) {
|
|
111
111
|
${w}
|
|
112
112
|
}
|
|
113
|
-
`;for(let u=0;u<n.length;u++){const o=n[u];let
|
|
114
|
-
${e.EntityInfo.ClassName}(${
|
|
113
|
+
`;for(let u=0;u<n.length;u++){const o=n[u];let l=o.Value;l&&o.EntityFieldInfo.TSType===y.EntityFieldTSType.Date&&(l=l.getTime()),l&&o.EntityFieldInfo.TSType===y.EntityFieldTSType.Boolean&&typeof l!="boolean"&&(l=parseInt(l)!==0),l===null&&o.EntityFieldInfo.AllowsNull===!1&&(o.EntityFieldInfo.DefaultValue!==null?l=o.EntityFieldInfo.DefaultValue:o.FieldType===y.EntityFieldTSType.Number||o.FieldType===y.EntityFieldTSType.Boolean?l=0:l=""),r.input[o.CodeName]=l}if(c.trim().toLowerCase()==="update"&&a.SkipOldValuesCheck===!1){const u=[];e.Fields.forEach(o=>{let l=null;o.OldValue!==null&&o.OldValue!==void 0&&(o.EntityFieldInfo.TSType===y.EntityFieldTSType.Date?l=o.OldValue.getTime().toString():o.EntityFieldInfo.TSType===y.EntityFieldTSType.Boolean?l=o.OldValue===!0?"1":"0":typeof o.OldValue!="string"?l=o.OldValue.toString():l=o.OldValue),u.push({Key:o.CodeName,Value:l})}),r.input.OldValues___=u}if(e.TransactionGroup)return new Promise((u,o)=>{const l=[{varName:"input",inputType:i+"Input!"}];e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new y.TransactionItem(e,w,r,{mutationName:i,mutationInputTypes:l},(p,D)=>{t.EndedAt=new Date,D&&p?(t.Success=!0,u(this.ConvertBackToMJFields(p))):(t.Success=!1,t.Message="Transaction failed",o())}))});{const u=await d.ExecuteGQL(m,r);if(u&&u[c+e.EntityInfo.ClassName])return t.Success=!0,t.EndedAt=new Date,this.ConvertBackToMJFields(u[c+e.EntityInfo.ClassName]);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,s,a=null,t){try{const r={};let c="",i="";for(let u=0;u<s.KeyValuePairs.length;u++){const o=e.Fields.find(D=>D.Name.trim().toLowerCase()===s.KeyValuePairs[u].FieldName.trim().toLowerCase()).EntityFieldInfo,l=s.GetValueByIndex(u),p=o.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${o.CodeName}: ${p}!`,c.length>0&&(c+=", "),c+=`${o.CodeName}: $${o.CodeName}`,o.TSType===y.EntityFieldTSType.Number){if(isNaN(s.GetValueByIndex(u)))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 n=a&&a.length>0?this.getRelatedEntityString(e.EntityInfo,a):"",f=new h,w=R.gql`query Single${e.EntityInfo.ClassName}${n.length>0?"Full":""} (${i}) {
|
|
114
|
+
${e.EntityInfo.ClassName}(${c}) {
|
|
115
115
|
${e.Fields.filter(u=>!u.EntityFieldInfo.IsBinaryFieldType).map(u=>u.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?u.CodeName.replace("__mj_","_mj__"):u.CodeName).join(`
|
|
116
116
|
`)}
|
|
117
117
|
${n}
|
|
118
118
|
}
|
|
119
119
|
}
|
|
120
|
-
`,
|
|
120
|
+
`,m=await d.ExecuteGQL(w,r);return m&&m[e.EntityInfo.ClassName]?this.ConvertBackToMJFields(m[e.EntityInfo.ClassName]):null}catch(r){return y.LogError(r),null}}ConvertBackToMJFields(e){return new h().ReverseMapFields(e),e}getRelatedEntityString(e,s){let a="";for(let t=0;t<e.RelatedEntities.length;t++)if(s.indexOf(e.RelatedEntities[t].RelatedEntity)>=0){const r=e.RelatedEntities[t],c=this.Entities.find(n=>n.ID===r.RelatedEntityID);let i="";r.Type.toLowerCase().trim()==="many to many"?i=`${r.RelatedEntityCodeName}_${r.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${r.RelatedEntityCodeName}_${r.RelatedEntityJoinField.replace(/\s/g,"")}`,a+=`
|
|
121
121
|
${i} {
|
|
122
|
-
${
|
|
122
|
+
${c.Fields.map(n=>n.CodeName).join(`
|
|
123
123
|
`)}
|
|
124
124
|
}
|
|
125
|
-
`}return a}async Delete(e,s,a){const t=new
|
|
126
|
-
`),f+=`${
|
|
125
|
+
`}return a}async Delete(e,s,a){const t=new y.BaseEntityResult;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={},c=[];let i="",n="",f="";for(let o of e.PrimaryKey.KeyValuePairs){const l=e.Fields.find(p=>p.Name.trim().toLowerCase()===o.FieldName.trim().toLowerCase());r[l.CodeName]=l.Value,c.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+=`
|
|
126
|
+
`),f+=`${l.CodeName}`}c.push({varName:"options___",inputType:"DeleteOptionsInput!"}),r.options___=s||{SkipEntityAIActions:!1,SkipEntityActions:!1};const w="Delete"+e.EntityInfo.ClassName,m=R.gql`${w}(${i}, options___: $options___) {
|
|
127
127
|
${f}
|
|
128
128
|
}
|
|
129
129
|
`,u=R.gql`mutation ${w} (${n}, $options___: DeleteOptionsInput!) {
|
|
130
|
-
${
|
|
130
|
+
${m}
|
|
131
131
|
}
|
|
132
|
-
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),new Promise((o,
|
|
132
|
+
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),new Promise((o,l)=>{e.TransactionGroup.AddTransaction(new y.TransactionItem(e,m,r,{mutationName:w,mutationInputTypes:c},(p,D)=>{if(t.EndedAt=new Date,D&&p){let E=!0;for(const P of e.PrimaryKey.KeyValuePairs)P.Value!==p[P.FieldName]&&(E=!1);E?(t.Success=!0,o(!0)):(t.Success=!1,t.Message="Transaction failed to commit",l())}else t.Success=!1,t.Message="Transaction failed to commit",l()}))});{const o=await d.ExecuteGQL(u,r);if(o&&o[w]){const l=o[w];for(let p of e.PrimaryKey.KeyValuePairs){let D=l[p.FieldName],E=p.Value;if(typeof E=="number"&&(E=E.toString()),typeof D=="number"&&(D=D.toString()),E!==D)throw new Error(`Primary key value mismatch in server Delete response. Field: ${p.FieldName}, Original: ${E}, 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,y.LogError(r),!1}}async GetDatasetByName(e,s){const a=R.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
133
133
|
GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
134
134
|
DatasetID
|
|
135
135
|
DatasetName
|
|
@@ -147,16 +147,16 @@
|
|
|
147
147
|
LatestUpdateDate
|
|
148
148
|
EntityUpdateDates
|
|
149
149
|
}
|
|
150
|
-
}`,t=await d.ExecuteGQL(a,{DatasetName:e,ItemFilters:s});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
|
|
150
|
+
}`,t=await d.ExecuteGQL(a,{DatasetName:e,ItemFilters:s});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 T}async GetRecordFavoriteStatus(e,s,a){if(!a.Validate().IsValid)return!1;const r=this.Entities.find(n=>n.Name===s);if(!r)throw new Error(`Entity ${s} not found in metadata`);const c=R.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
|
|
151
151
|
GetRecordFavoriteStatus(params: $params) {
|
|
152
152
|
Success
|
|
153
153
|
IsFavorite
|
|
154
154
|
}
|
|
155
|
-
}`,i=await d.ExecuteGQL(
|
|
155
|
+
}`,i=await d.ExecuteGQL(c,{params:{UserID:e,EntityID:r.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(a.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,s,a,t,r){const c=this.Entities.find(f=>f.Name===s);if(!c)throw new Error(`Entity ${s} not found in metadata`);const i=R.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
|
|
156
156
|
SetRecordFavoriteStatus(params: $params){
|
|
157
157
|
Success
|
|
158
158
|
}
|
|
159
|
-
}`,n=await d.ExecuteGQL(i,{params:{UserID:e,EntityID:
|
|
159
|
+
}`,n=await d.ExecuteGQL(i,{params:{UserID:e,EntityID:c.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(a.KeyValuePairs)},IsFavorite:t}});if(n&&n.SetRecordFavoriteStatus!==null)return n.SetRecordFavoriteStatus.Success}async GetEntityRecordName(e,s){if(!e||!s||s.KeyValuePairs?.length===0)return null;const a=R.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
160
160
|
GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
|
|
161
161
|
Success
|
|
162
162
|
Status
|
|
@@ -175,18 +175,18 @@
|
|
|
175
175
|
EntityName
|
|
176
176
|
RecordName
|
|
177
177
|
}
|
|
178
|
-
}`,a=await d.ExecuteGQL(s,{info:e.map(t=>({EntityName:t.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.CompositeKey.KeyValuePairs)}}))});if(a&&a.GetEntityRecordNames)return a.GetEntityRecordNames}static async ExecuteGQL(e,s,a=!0){try{return await d._client.request(e,s)}catch(t){if(t&&t.response&&t.response.errors?.length>0)if(t.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(a)return await d.RefreshToken(),await d.ExecuteGQL(e,s,!1);throw
|
|
178
|
+
}`,a=await d.ExecuteGQL(s,{info:e.map(t=>({EntityName:t.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.CompositeKey.KeyValuePairs)}}))});if(a&&a.GetEntityRecordNames)return a.GetEntityRecordNames}static async ExecuteGQL(e,s,a=!0){try{return await d._client.request(e,s)}catch(t){if(t&&t.response&&t.response.errors?.length>0)if(t.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(a)return await d.RefreshToken(),await d.ExecuteGQL(e,s,!1);throw y.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),t}else throw t;else throw y.LogError(t),t}}static async RefreshToken(){if(d._configData.Data.RefreshTokenFunction){const e=await d._configData.Data.RefreshTokenFunction();if(e)d._configData.Token=e,d._client=this.CreateNewGraphQLClient(d._configData.URL,d._configData.Token,d._sessionId);else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static CreateNewGraphQLClient(e,s,a){return new R.GraphQLClient(e,{headers:{authorization:"Bearer "+s,"x-session-id":a}})}userInfoString(){return this.infoString(new y.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new y.UserRoleInfo(null))}infoString(e){let s="";const a=Object.keys(e);for(const t of a)t.startsWith("__mj_")?s+=t.replace("__mj_","_mj__")+`
|
|
179
179
|
`:t.startsWith("_")||(s+=t+`
|
|
180
|
-
`);return s}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new
|
|
180
|
+
`);return s}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new C),this._localStorageProvider}get Metadata(){return this}PushStatusUpdates(e=null){e||(e=this.sessionId),this._wsClient||(this._wsClient=B.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}}));const s=this._pushStatusRequests.find(r=>r.sessionId===e);if(s)return s.observable;const a=R.gql`subscription StatusUpdates($sessionId: String!) {
|
|
181
181
|
statusUpdates(sessionId: $sessionId) {
|
|
182
182
|
date
|
|
183
183
|
message
|
|
184
184
|
sessionId
|
|
185
185
|
}
|
|
186
186
|
}
|
|
187
|
-
`,t=new Q.Observable(r=>(this._wsClient.subscribe({query:a,variables:{sessionId:e}},{next:
|
|
187
|
+
`,t=new Q.Observable(r=>(this._wsClient.subscribe({query:a,variables:{sessionId:e}},{next:c=>r.next(c.data.statusUpdates),error:c=>r.error(c),complete:()=>r.complete()}),()=>{console.log("would unsub here")}));return this._pushStatusRequests.push({sessionId:e,observable:t}),t}};g(d,"GraphQLDataProvider");let S=d;const v=class v{constructor(){this._localStorage={}}async getItem(e){return new Promise(s=>{this._localStorage.hasOwnProperty(e)?s(this._localStorage[e]):s(null)})}async setItem(e,s){return new Promise(a=>{this._localStorage[e]=s,a()})}async remove(e){return new Promise(s=>{this._localStorage.hasOwnProperty(e)&&delete this._localStorage[e],s()})}};g(v,"BrowserStorageProviderBase");let F=v;const k="MJ_Metadata",N="Metadata_KVPairs",G=class G extends F{constructor(){super(),this.dbPromise=q.openDB(k,1,{upgrade(e){e.objectStoreNames.contains(N)||e.createObjectStore(N)}})}async setItem(e,s){const t=(await this.dbPromise).transaction(N,"readwrite");await t.objectStore(N).put(s,e),await t.done}async getItem(e){return await(await this.dbPromise).transaction(N).objectStore(N).get(e)}async remove(e){const a=(await this.dbPromise).transaction(N,"readwrite");await a.objectStore(N).delete(e),await a.done}};g(G,"BrowserIndexedDBStorageProvider");let C=G;const L=class L extends y.TransactionGroupBase{async HandleSubmit(e){let s="",a="";const t={};for(let i=0;i<e.length;i++){const n=e[i];let f=n.Instruction;if(n.Vars){const w=Object.keys(n.Vars);for(let m=0;m<w.length;m++){const u=w[m],o=`${u}_${i}`;t[o]=n.Vars[u];const l=new RegExp("\\$"+u,"g");f=f.replace(l,"$"+o);const p=n.ExtraData.mutationInputTypes.find(D=>D.varName===u)?.inputType;a+=`$${o}: ${p}
|
|
188
188
|
`}}s+=`mutation_${i}: `+f+`
|
|
189
189
|
`}s=`mutation TransactionGroup(${a}){
|
|
190
190
|
`+s+`
|
|
191
|
-
}`;const r=await S.ExecuteGQL(s,t),
|
|
191
|
+
}`;const r=await S.ExecuteGQL(s,t),c=[];for(let i=0;i<e.length;i++){const n=r[`mutation_${i}`],f=e[i];c.push(new y.TransactionResult(f,n,n!==null))}return c}};g(L,"GraphQLTransactionGroup");let T=L;async function K(I){const e=new S;return y.BaseEntity.Provider=e,y.Metadata.Provider=e,y.RunView.Provider=e,y.RunReport.Provider=e,y.RunQuery.Provider=e,await e.Config(I),M.MJGlobal.Instance.RaiseEvent({event:M.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}g(K,"setupGraphQLClient"),Object.defineProperty(exports,"gql",{enumerable:!0,get:function(){return R.gql}}),exports.FieldMapper=h,exports.GraphQLDataProvider=S,exports.GraphQLProviderConfigData=V,exports.setupGraphQLClient=K;
|
|
192
192
|
//# sourceMappingURL=index.cjs.map
|