@memberjunction/graphql-dataprovider 2.14.0 → 2.15.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 +17 -17
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +8 -8
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var B=Object.defineProperty;var E=(V,e)=>B(V,"name",{value:e,configurable:!0});import{gql as w,GraphQLClient as A}from"graphql-request";import{gql as
|
|
1
|
+
var B=Object.defineProperty;var E=(V,e)=>B(V,"name",{value:e,configurable:!0});import{gql as w,GraphQLClient as A}from"graphql-request";import{gql as pe}from"graphql-request";import{ProviderConfigDataBase as K,ProviderBase as O,LogError as h,UserInfo as U,ProviderType as q,BaseEntityResult as M,EntityFieldTSType as g,TransactionItem as k,UserRoleInfo as b,TransactionGroupBase as J,TransactionResult as j,SetProvider as W}from"@memberjunction/core";import{ViewInfo as Q}from"@memberjunction/core-entities";import{openDB as z}from"@tempfix/idb";import{Observable as H}from"rxjs";import{createClient as X}from"graphql-ws";import{v4 as Z}from"uuid";import{MJGlobal as Y,MJEventType as ee}from"@memberjunction/global";const G=class G{constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const 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}};E(G,"FieldMapper");let I=G;const _=class _ extends K{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,a,s,t,r,c,n){super({Token:e,URL:a,WSURL:s,RefreshTokenFunction:t},r,c,n)}};E(_,"GraphQLProviderConfigData");let C=_;const R=class R extends O{constructor(){super(),this._innerCurrentUserQueryString=`CurrentUser {
|
|
2
2
|
${this.userInfoString()}
|
|
3
3
|
UserRoles_UserIDArray {
|
|
4
4
|
${this.userRoleInfoString()}
|
|
@@ -6,7 +6,7 @@ var B=Object.defineProperty;var E=(V,e)=>B(V,"name",{value:e,configurable:!0});i
|
|
|
6
6
|
}
|
|
7
7
|
`,this._currentUserQuery=w`query CurrentUserAndRoles {
|
|
8
8
|
${this._innerCurrentUserQueryString}
|
|
9
|
-
}`,this._wsClient=null,this._pushStatusRequests=[],R._instance||(R._instance=this)}static get Instance(){return R._instance}get ConfigData(){return this._configData}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}GenerateUUID(){return
|
|
9
|
+
}`,this._wsClient=null,this._pushStatusRequests=[],R._instance||(R._instance=this)}static get Instance(){return R._instance}get ConfigData(){return this._configData}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}GenerateUUID(){return Z()}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)):(R.Instance._sessionId===void 0&&(R.Instance._sessionId=s),R.Instance._configData=e,R.Instance._client||(R.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,R.Instance._sessionId))),super.Config(e)}catch(s){throw h(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 U(this,{...a,UserRoles:s})}}async RunReport(e,a){const s=w`
|
|
10
10
|
query GetReportDataQuery ($ReportID: String!) {
|
|
11
11
|
GetReportData(ReportID: $ReportID) {
|
|
12
12
|
Success
|
|
@@ -53,7 +53,7 @@ var B=Object.defineProperty;var E=(V,e)=>B(V,"name",{value:e,configurable:!0});i
|
|
|
53
53
|
Success
|
|
54
54
|
ErrorMessage
|
|
55
55
|
}
|
|
56
|
-
}`,n=await this.ExecuteGQL(c,{input:s});if(n&&n.RunViews){const i=n.RunViews;for(const[y,p]of i.entries())p.Results=p.Results.map(d=>{let u=JSON.parse(d.Data);return this.ConvertBackToMJFields(u),u});return i}return null}catch(s){throw h(s),s}}async getEntityNameAndUserView(e,a){let s,t;if(e.EntityName)s=e.EntityName;else if(e.ViewID)t=await
|
|
56
|
+
}`,n=await this.ExecuteGQL(c,{input:s});if(n&&n.RunViews){const i=n.RunViews;for(const[y,p]of i.entries())p.Results=p.Results.map(d=>{let u=JSON.parse(d.Data);return this.ConvertBackToMJFields(u),u});return i}return null}catch(s){throw h(s),s}}async getEntityNameAndUserView(e,a){let s,t;if(e.EntityName)s=e.EntityName;else if(e.ViewID)t=await Q.GetViewEntity(e.ViewID,a),s=t.Entity;else if(e.ViewName)t=await Q.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=[],c=new I;if(s.Fields){for(const n of e.PrimaryKeys)s.Fields.find(i=>i.trim().toLowerCase()===n.Name.toLowerCase())===void 0&&r.push(n.Name);s.Fields.forEach(n=>{r.push(c.MapFieldName(n))})}else if(t)e.Fields.forEach(n=>{n.IsBinaryFieldType||r.push(c.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(c.MapFieldName(n.EntityField.CodeName))})}return r}get ProviderType(){return q.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,c)=>r.ChangedAt>c.ChangedAt?-1:1):null}catch(s){throw h(s),s}}async GetRecordDependencies(e,a){try{const s=w`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
57
57
|
GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
|
|
58
58
|
EntityName
|
|
59
59
|
RelatedEntityName
|
|
@@ -110,7 +110,7 @@ var B=Object.defineProperty;var E=(V,e)=>B(V,"name",{value:e,configurable:!0});i
|
|
|
110
110
|
}`,d=w`mutation ${c}${e.EntityInfo.ClassName} ($input: ${n}Input!) {
|
|
111
111
|
${p}
|
|
112
112
|
}
|
|
113
|
-
`;for(let u=0;u<i.length;u++){const o=i[u];let l=o.Value;l&&o.EntityFieldInfo.TSType===g.Date&&(l=l.getTime()),l&&o.EntityFieldInfo.TSType===g.Boolean&&typeof l!="boolean"&&(l=parseInt(l)!==0),l===null&&o.EntityFieldInfo.AllowsNull===!1&&(o.EntityFieldInfo.DefaultValue!==null?l=o.EntityFieldInfo.DefaultValue:o.FieldType===g.Number||o.FieldType===g.Boolean?l=0:l=""),r.input[o.CodeName]=l}if(c.trim().toLowerCase()==="update"&&s.SkipOldValuesCheck===!1){const u=[];e.Fields.forEach(o=>{let l=null;o.OldValue!==null&&o.OldValue!==void 0&&(o.EntityFieldInfo.TSType===g.Date?l=o.OldValue.getTime().toString():o.EntityFieldInfo.TSType===g.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:n+"Input!"}];e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new
|
|
113
|
+
`;for(let u=0;u<i.length;u++){const o=i[u];let l=o.Value;l&&o.EntityFieldInfo.TSType===g.Date&&(l=l.getTime()),l&&o.EntityFieldInfo.TSType===g.Boolean&&typeof l!="boolean"&&(l=parseInt(l)!==0),l===null&&o.EntityFieldInfo.AllowsNull===!1&&(o.EntityFieldInfo.DefaultValue!==null?l=o.EntityFieldInfo.DefaultValue:o.FieldType===g.Number||o.FieldType===g.Boolean?l=0:l=""),r.input[o.CodeName]=l}if(c.trim().toLowerCase()==="update"&&s.SkipOldValuesCheck===!1){const u=[];e.Fields.forEach(o=>{let l=null;o.OldValue!==null&&o.OldValue!==void 0&&(o.EntityFieldInfo.TSType===g.Date?l=o.OldValue.getTime().toString():o.EntityFieldInfo.TSType===g.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:n+"Input!"}];e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new k(e,p,r,{mutationName:n,mutationInputTypes:l},(m,f)=>{t.EndedAt=new Date,f&&m?(t.Success=!0,u(this.ConvertBackToMJFields(m))):(t.Success=!1,t.Message="Transaction failed",o())}))});{const u=await this.ExecuteGQL(d,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,h(r),null}}async Load(e,a,s=null,t){try{const r={};let c="",n="";for(let u=0;u<a.KeyValuePairs.length;u++){const o=e.Fields.find(f=>f.Name.trim().toLowerCase()===a.KeyValuePairs[u].FieldName.trim().toLowerCase()).EntityFieldInfo,l=a.GetValueByIndex(u),m=o.GraphQLType;if(n.length>0&&(n+=", "),n+=`$${o.CodeName}: ${m}!`,c.length>0&&(c+=", "),c+=`${o.CodeName}: $${o.CodeName}`,o.TSType===g.Number){if(isNaN(a.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 i=s&&s.length>0?this.getRelatedEntityString(e.EntityInfo,s):"",y=new I,p=w`query Single${e.EntityInfo.ClassName}${i.length>0?"Full":""} (${n}) {
|
|
114
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
|
`)}
|
|
@@ -129,7 +129,7 @@ var B=Object.defineProperty;var E=(V,e)=>B(V,"name",{value:e,configurable:!0});i
|
|
|
129
129
|
`,u=w`mutation ${p} (${i}, $options___: DeleteOptionsInput!) {
|
|
130
130
|
${d}
|
|
131
131
|
}
|
|
132
|
-
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),new Promise((o,l)=>{e.TransactionGroup.AddTransaction(new
|
|
132
|
+
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),new Promise((o,l)=>{e.TransactionGroup.AddTransaction(new k(e,d,r,{mutationName:p,mutationInputTypes:c},(m,f)=>{if(t.EndedAt=new Date,f&&m){let D=!0;for(const P of e.PrimaryKey.KeyValuePairs)P.Value!==m[P.FieldName]&&(D=!1);D?(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 this.ExecuteGQL(u,r);if(o&&o[p]){const l=o[p];for(let m of e.PrimaryKey.KeyValuePairs){let f=l[m.FieldName],D=m.Value;if(typeof D=="number"&&(D=D.toString()),typeof f=="number"&&(f=f.toString()),D!==f)throw new Error(`Primary key value mismatch in server Delete response. Field: ${m.FieldName}, Original: ${D}, Returned: ${f}`)}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,h(r),!1}}async GetDatasetByName(e,a){const s=w`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
133
133
|
GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
134
134
|
DatasetID
|
|
135
135
|
DatasetName
|
|
@@ -177,16 +177,16 @@ var B=Object.defineProperty;var E=(V,e)=>B(V,"name",{value:e,configurable:!0});i
|
|
|
177
177
|
}
|
|
178
178
|
}`,s=await this.ExecuteGQL(a,{info:e.map(t=>({EntityName:t.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.CompositeKey.KeyValuePairs)}}))});if(s&&s.GetEntityRecordNames)return s.GetEntityRecordNames}static async ExecuteGQL(e,a,s=!0){return R.Instance.ExecuteGQL(e,a,s)}async ExecuteGQL(e,a,s=!0){try{return await this._client.request(e,a)}catch(t){if(t&&t.response&&t.response.errors?.length>0)if(t.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(s)return await this.RefreshToken(),await this.ExecuteGQL(e,a,!1);throw h("JWT_EXPIRED and refreshTokenIfNeeded is false"),t}else throw t;else throw h(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);else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static async RefreshToken(){return R.Instance.RefreshToken()}CreateNewGraphQLClient(e,a,s){return new A(e,{headers:{authorization:"Bearer "+a,"x-session-id":s}})}userInfoString(){return this.infoString(new U(null,null))}userRoleInfoString(){return this.infoString(new b(null))}infoString(e){let a="";const s=Object.keys(e);for(const t of s)t.startsWith("__mj_")?a+=t.replace("__mj_","_mj__")+`
|
|
179
179
|
`:t.startsWith("_")||(a+=t+`
|
|
180
|
-
`);return a}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new $),this._localStorageProvider}get Metadata(){return this}PushStatusUpdates(e=null){e||(e=this.sessionId),this._wsClient||(this._wsClient=
|
|
180
|
+
`);return a}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new $),this._localStorageProvider}get Metadata(){return this}PushStatusUpdates(e=null){e||(e=this.sessionId),this._wsClient||(this._wsClient=X({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=w`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
|
|
187
|
+
`,t=new H(r=>(this._wsClient.subscribe({query:s,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}};E(R,"GraphQLDataProvider");let S=R;const v=class v{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()})}};E(v,"BrowserStorageProviderBase");let F=v;const te="MJ_Metadata",N="Metadata_KVPairs",L=class L extends F{constructor(){super(),this.dbPromise=z(te,1,{upgrade(e){e.objectStoreNames.contains(N)||e.createObjectStore(N)}})}async setItem(e,a){const t=(await this.dbPromise).transaction(N,"readwrite");await t.objectStore(N).put(a,e),await t.done}async getItem(e){return await(await this.dbPromise).transaction(N).objectStore(N).get(e)}async remove(e){const s=(await this.dbPromise).transaction(N,"readwrite");await s.objectStore(N).delete(e),await s.done}};E(L,"BrowserIndexedDBStorageProvider");let $=L;const x=class x extends J{constructor(e){super()}async HandleSubmit(e){let a="",s="";const t={};for(let n=0;n<e.length;n++){const i=e[n];let y=i.Instruction;if(i.Vars){const p=Object.keys(i.Vars);for(let d=0;d<p.length;d++){const u=p[d],o=`${u}_${n}`;t[o]=i.Vars[u];const l=new RegExp("\\$"+u,"g");y=y.replace(l,"$"+o);const m=i.ExtraData.mutationInputTypes.find(f=>f.varName===u)?.inputType;s+=`$${o}: ${m}
|
|
188
188
|
`}}a+=`mutation_${n}: `+y+`
|
|
189
189
|
`}a=`mutation TransactionGroup(${s}){
|
|
190
190
|
`+a+`
|
|
191
|
-
}`;const r=await this._provider.ExecuteGQL(a,t),c=[];for(let n=0;n<e.length;n++){const i=r[`mutation_${n}`],y=e[n];c.push(new j(y,i,i!==null))}return c}};E(
|
|
191
|
+
}`;const r=await this._provider.ExecuteGQL(a,t),c=[];for(let n=0;n<e.length;n++){const i=r[`mutation_${n}`],y=e[n];c.push(new j(y,i,i!==null))}return c}};E(x,"GraphQLTransactionGroup");let T=x;async function se(V){const e=new S;return W(e),await e.Config(V),Y.Instance.RaiseEvent({event:ee.LoggedIn,eventCode:null,component:this,args:null}),e}E(se,"setupGraphQLClient");export{I as FieldMapper,S as GraphQLDataProvider,C as GraphQLProviderConfigData,pe as gql,se as setupGraphQLClient};
|
|
192
192
|
//# sourceMappingURL=index.mjs.map
|