@jsb188/graphql 1.0.2 → 1.1.1

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/cache/config.ts CHANGED
@@ -18,6 +18,8 @@ export const RULES = {
18
18
 
19
19
  // List of queries that should be cached
20
20
  // NOTE: Fragments are always cached
21
+ aiChat: true,
22
+ aiChatMessages: true,
21
23
  alerts: true,
22
24
  cardsForUser: true,
23
25
  chat: true,
@@ -34,7 +36,8 @@ export const RULES = {
34
36
 
35
37
  // All fragments are cached,
36
38
  // but if you want to skip some, add it here
37
- authFragment: false,
39
+ accountAuthFragment: false,
40
+ userAuthFragment: false,
38
41
  } as {
39
42
  __limit: number;
40
43
  [key: string]: boolean | number;
package/cache/index.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { cloneArrayLike } from '@jsb188/app/utils/object';
1
2
  import type { UpdateObserversFn } from '../types.d';
2
3
  import { RULES, PARTIALS_MAP } from './config';
3
4
 
@@ -61,28 +62,13 @@ export function mergeNestedObjects(obj1: any, obj2: any) {
61
62
  return newObj;
62
63
  }
63
64
 
64
- /**
65
- * Check if Object is array-like, then convert to plain Object.
66
- * NOTE: This happens a lot when using JS Map()
67
- * NOTE: This assumes that the keys are ordered numbers
68
- * NOTE: This function always clones the object.
69
- */
70
-
71
- export function cloneArrayLike(obj: any) {
72
- if (
73
- !Array.isArray(obj) &&
74
- Object.keys(obj).every((key, i) => key === i.toString())
75
- ) {
76
- return Object.values(obj);
77
- }
78
- return { ...obj };
79
- }
80
-
81
65
  /**
82
66
  * Get a single string to represent all variables for a query
83
67
  * NOTE: This isn't perfect because variables could have extra or unnnecessary keys/values
84
68
  * The correct way to do this would be to compare it against the query {variableDefinitions}
85
69
  * But this will work as long as each variables object is used consistently to match the used query.
70
+ *
71
+ * NOTE: Same logic is used in SSE [publish.ts]
86
72
  */
87
73
 
88
74
  export function makeVariablesKey(variables?: any) {
@@ -130,6 +116,7 @@ function extractFragment(dataObj: any, innerSelection: any[]) {
130
116
 
131
117
  export function loadQuery(queryKey: string, referencesOnly?: boolean) {
132
118
  const references = QUERIES.get(queryKey);
119
+
133
120
  if (referencesOnly) {
134
121
  return references;
135
122
  } else if (!references) {
@@ -315,7 +302,7 @@ function makeCacheObject(data: any, selections: any[], variables?: any, cacheMap
315
302
  */
316
303
 
317
304
  function saveQueryToMemory(
318
- requestData: any | null,
305
+ requestData: any,
319
306
  selection: any,
320
307
  variables: any,
321
308
  variablesKey: string,
@@ -328,6 +315,9 @@ function saveQueryToMemory(
328
315
  return;
329
316
  }
330
317
 
318
+ // IMPORTANT NOTE:
319
+ // Queries are never cached unless they are manually set in [./config.ts]
320
+
331
321
  const data = requestData[qryName];
332
322
  const queryId = `#${qryName}:${variablesKey}`;
333
323
  const selections = selection?.selectionSet?.selections;
@@ -362,8 +352,7 @@ function saveQueryToMemory(
362
352
  // cacheMap[key](data[key], cacheObj[key], sel, variables);
363
353
  if (saveQueryToCache) {
364
354
  const customCacheData = cacheMap(data, cacheData, selections, variables);
365
- // console.log('--->', queryId);
366
-
355
+ // console.log('1--->', queryId);
367
356
  QUERIES.set(queryId, typeof customCacheData === 'undefined' ? null : customCacheData);
368
357
 
369
358
  if (updateObservers) {
@@ -374,7 +363,8 @@ function saveQueryToMemory(
374
363
  }
375
364
  } else {
376
365
  if (saveQueryToCache) {
377
- // console.log('--->', queryId);
366
+ // console.log('2--->', queryId);
367
+ // console.log('2--->', cacheData);
378
368
  QUERIES.set(queryId, cacheData);
379
369
  }
380
370
 
@@ -448,10 +438,11 @@ export function appendFragmentToCache(cacheData: any) {
448
438
  let cacheIsValid = true;
449
439
 
450
440
  if (newObj[key].__list) {
451
- cachedObj = newObj[key].data.map((di) => {
441
+ cachedObj = newObj[key].data.map((di: any[]) => {
452
442
  let item = {};
453
443
  di.forEach((d) => {
454
444
  if (Array.isArray(d)) {
445
+ // @ts-expect-error
455
446
  item[d[0]] = d[1];
456
447
  } else if (typeof d === 'string') {
457
448
  const frgIndex = d.indexOf(':');
@@ -488,8 +479,9 @@ export function appendFragmentToCache(cacheData: any) {
488
479
  return item;
489
480
  });
490
481
  } else {
491
- newObj[key].data.forEach((d) => {
482
+ newObj[key].data.forEach((d: any) => {
492
483
  if (Array.isArray(d)) {
484
+ // @ts-expect-error
493
485
  cachedObj[d[0]] = d[1];
494
486
  } else if (typeof d === 'string') {
495
487
  const frgIndex = d.indexOf(':');
@@ -562,7 +554,7 @@ export function loadDataFromCache(
562
554
 
563
555
  for (const def of definitions) {
564
556
  if (def.kind === 'OperationDefinition') {
565
- def?.selectionSet?.selections.forEach((selection) => {
557
+ def?.selectionSet?.selections.forEach((selection: any) => {
566
558
  const qryName = selection.name?.value;
567
559
  if (!data[qryName]) {
568
560
  const cacheKey = `#${qryName}:${variablesKey}`;
@@ -758,13 +750,13 @@ export function resetQuery(queryId: string, forceRefetch?: boolean, updateObserv
758
750
  */
759
751
 
760
752
  export function updateFragment(
761
- id: string,
762
- update: any | ((cache: any) => object),
753
+ updateFragmentKey: string,
754
+ update: any | ((cache: any) => any),
763
755
  replaceId?: string | null,
764
756
  doNotTriggerObserver?: boolean,
765
757
  updateObservers?: UpdateObserversFn,
766
758
  ) {
767
- const cache = loadFragment(id);
759
+ const cache = loadFragment(updateFragmentKey);
768
760
 
769
761
  if (cache && update) {
770
762
  let updateObj;
@@ -776,9 +768,9 @@ export function updateFragment(
776
768
 
777
769
  const updatedObj = { ...cache, ...updateObj };
778
770
 
779
- FRAGMENTS.set(id, updatedObj);
771
+ FRAGMENTS.set(updateFragmentKey, updatedObj);
780
772
 
781
- if (replaceId && replaceId !== id) {
773
+ if (replaceId && replaceId !== updateFragmentKey) {
782
774
  FRAGMENTS.set(replaceId, updatedObj);
783
775
 
784
776
  // Must be deleted later, for the observer to work properly
@@ -787,15 +779,15 @@ export function updateFragment(
787
779
 
788
780
  if (!doNotTriggerObserver && updateObservers) {
789
781
  updateObservers({
790
- fragmentIds: [id],
782
+ fragmentIds: [updateFragmentKey],
791
783
  });
792
784
 
793
785
  // FRAGMENT_OBSERVER.value = {
794
786
  // count: FRAGMENT_OBSERVER.value.count + 1,
795
- // list: [id],
787
+ // list: [updateFragmentKey],
796
788
  // };
797
789
  }
798
- return id || null;
790
+ return updateFragmentKey || null;
799
791
  }
800
792
  return null;
801
793
  }
@@ -806,7 +798,7 @@ export function updateFragment(
806
798
 
807
799
  export function updateQuery(
808
800
  queryId: string,
809
- update: any | ((cache: any) => object),
801
+ update: any | ((cache: any) => any),
810
802
  doNotTriggerObserver?: boolean,
811
803
  updateObservers?: UpdateObserversFn,
812
804
  ) {
@@ -0,0 +1,2 @@
1
+ export * from '../hooks/index';
2
+ export * from './request';
@@ -0,0 +1,195 @@
1
+ import { getENVVariable } from '@jsb188/app';
2
+ import type { ServerErrorObj } from '@jsb188/app/types/app.d';
3
+ import { getAuthToken, normalizeServerError } from '@jsb188/app/utils/api';
4
+ import { delay } from '@jsb188/app/utils/logic';
5
+ import { setDataToCache } from '../cache/';
6
+ import type { OnCompletedGQLFn, OnErrorGQLFn, UpdateObserversFn } from '../types.d';
7
+ import { apiRequestHeaders, isServerErrorGQL } from '../utils';
8
+
9
+ /**
10
+ * Types
11
+ */
12
+
13
+ type GraphQLMutationOptions = Partial<{
14
+ authToken: string;
15
+ ipAddress: string | null; // Only used if SSR
16
+ retryCount: number;
17
+ variables: any;
18
+ cacheMap: any;
19
+ openModalPopUp: any;
20
+ initialError: any;
21
+ onCompleted: OnCompletedGQLFn;
22
+ onError: OnErrorGQLFn;
23
+ }>;
24
+
25
+ /**
26
+ * Helper: Get name of query
27
+ */
28
+
29
+ // function getQueryName(query: any) {
30
+ // return query.definitions.filter((d: any) => d.kind === 'OperationDefinition').map(d => d.name.value).join(', ');
31
+ // }
32
+
33
+ /**
34
+ * Helper; Log if conditions are met
35
+ */
36
+
37
+ // function doLog(query: any, logStr: string) {
38
+ // const queryName = getQueryName(query);
39
+ // if (queryName === 'friend') {
40
+ // console.log(logStr.replace(/\$0/gi, queryName));
41
+ // }
42
+ // }
43
+
44
+ /**
45
+ * Default params for graphql requests
46
+ */
47
+
48
+ const defaultRequestParams = {
49
+ // onCompleted: (data: any) => {
50
+ // if (getENVVariable('NODE_ENV') === 'development') {
51
+ // console.log('onCompleted:', data);
52
+ // }
53
+ // },
54
+ onError: (error: ServerErrorObj | null) => {
55
+ if (getENVVariable('NODE_ENV') === 'development') {
56
+ console.log('DEVELOPMENT onError():', error);
57
+ }
58
+ },
59
+ };
60
+
61
+ /**
62
+ * GraphQL request with retry support
63
+ */
64
+
65
+ export async function graphqlRequestWithRetry(
66
+ gqlQuery: any,
67
+ graphqlOptions: GraphQLMutationOptions = defaultRequestParams,
68
+ triedCount: number = 0,
69
+ ): Promise<any> {
70
+
71
+ const retryCount = graphqlOptions?.retryCount || 0;
72
+ const retryDelay = 1500 * Math.pow(2, triedCount);
73
+ const { onCompleted, onError, openModalPopUp } = graphqlOptions;
74
+
75
+ const apiResult = await graphqlRequest(
76
+ gqlQuery,
77
+ graphqlOptions?.variables,
78
+ {
79
+ openModalPopUp: retryCount >= triedCount ? openModalPopUp : undefined,
80
+ onCompleted: (data: any | null, error: ServerErrorObj | null) => {
81
+ if (onCompleted && data.data) {
82
+ onCompleted(data.data, error, graphqlOptions?.variables);
83
+ }
84
+ },
85
+ onError: (error: ServerErrorObj | null) => {
86
+ if (onError && retryCount <= triedCount) {
87
+ onError(error, graphqlOptions?.variables);
88
+ } else if (!onError) {
89
+ console.warn(error);
90
+ }
91
+ },
92
+ }
93
+ );
94
+
95
+ if (!apiResult.data && isServerErrorGQL(apiResult)) {
96
+ if (retryCount > triedCount) {
97
+ await delay(retryDelay);
98
+ if (getENVVariable('NODE_ENV') === 'development') {
99
+ console.log(`retrying mutation... ${triedCount + 1} / ${retryCount}`);
100
+ }
101
+
102
+ return graphqlRequestWithRetry(gqlQuery, graphqlOptions, triedCount + 1);
103
+ } else if (getENVVariable('NODE_ENV') === 'development') {
104
+ console.log(
105
+ `mutation failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`,
106
+ );
107
+ }
108
+ }
109
+
110
+ return apiResult.data || apiResult;
111
+ }
112
+
113
+ /**
114
+ * GraphQL query
115
+ */
116
+
117
+ export async function graphqlRequest(
118
+ gqlQuery: any,
119
+ variables?: any,
120
+ params?: GraphQLMutationOptions,
121
+ controllerSignal?: AbortSignal | null,
122
+ updateObservers?: UpdateObserversFn,
123
+ ): Promise<any> {
124
+
125
+ const { openModalPopUp, onCompleted, onError, authToken, cacheMap, ipAddress } = params || {};
126
+
127
+ if (!gqlQuery?.definitions) {
128
+ console.log(gqlQuery);
129
+ }
130
+
131
+ const operationName = gqlQuery?.definitions?.find((def: any) => def.kind === 'OperationDefinition')?.name?.value;
132
+ const headers = apiRequestHeaders(getENVVariable('IS_BROWSER') ? getAuthToken() : authToken, ipAddress);
133
+
134
+ // Use this to check queries that are getting double-requested
135
+ // doLog(gqlQuery, 'QUERYING... $0');
136
+
137
+ return fetch(getENVVariable('GQL_SERVER') as string, {
138
+ signal: controllerSignal,
139
+ method: 'POST',
140
+ // credentials: 'same-origin',
141
+ // headers: new Headers({
142
+ headers,
143
+ // headers,
144
+ body: JSON.stringify({
145
+ query: gqlQuery?.loc?.source.body,
146
+ variables,
147
+ operationName,
148
+ }),
149
+ })
150
+ .then((response) => response.json())
151
+ .then((data) => {
152
+ let gqlError: ServerErrorObj | null = null;
153
+ if (data.errors?.length) {
154
+ gqlError = normalizeServerError(data);
155
+
156
+ if (openModalPopUp) {
157
+ openModalPopUp(null, gqlError);
158
+ }
159
+
160
+ if (onError) {
161
+ onError(gqlError, variables);
162
+ }
163
+ }
164
+
165
+ if (onCompleted) {
166
+ onCompleted(data, gqlError, variables);
167
+ }
168
+
169
+ setDataToCache(data.data, gqlQuery, variables, cacheMap, updateObservers);
170
+
171
+ return {
172
+ ...data.data,
173
+ error: gqlError,
174
+ };
175
+ })
176
+ .catch((err) => {
177
+ if (getENVVariable('NODE_ENV') === 'development') {
178
+ console.log(err);
179
+ }
180
+
181
+ if (err.name === 'AbortError') {
182
+ return { aborted: true };
183
+ }
184
+
185
+ const gqlError = normalizeServerError(err);
186
+ if (openModalPopUp) {
187
+ openModalPopUp(null, gqlError);
188
+ }
189
+
190
+ if (onError) {
191
+ onError(gqlError, variables);
192
+ }
193
+ return { error: gqlError };
194
+ });
195
+ }
@@ -0,0 +1,16 @@
1
+ export const accountAuthFragment = `fragment accountAuthFragment on AccountAuth {
2
+ token
3
+ primaryOrganizationId
4
+ activated
5
+ hasPassword
6
+ version
7
+
8
+ settings {
9
+ theme
10
+ lightMode
11
+ timeZone
12
+ showSelfAvatar
13
+ isBubbleOther
14
+ showOtherAvatar
15
+ }
16
+ }`;
@@ -0,0 +1,10 @@
1
+ export const accountFragment = `fragment accountFragment on Account {
2
+ id
3
+ deleted
4
+
5
+ profile {
6
+ id
7
+ firstName
8
+ lastName
9
+ }
10
+ }`;
@@ -1,5 +1,8 @@
1
1
  export const aiChatFragment = `fragment aiChatFragment on AIChat {
2
2
  id
3
+ organizationId
4
+ accountId
5
+ calDate
3
6
  summary
4
7
  createdAt
5
8
  updatedAt
@@ -7,7 +10,8 @@ export const aiChatFragment = `fragment aiChatFragment on AIChat {
7
10
 
8
11
  export const aiChatMessageFragment = `fragment aiChatMessageFragment on AIChatMessage {
9
12
  id
10
- userId
13
+ accountId
14
+ type
11
15
  cursor
12
16
  text
13
17
  photoUri
@@ -0,0 +1,14 @@
1
+
2
+ export const journalEntryFragment = `fragment journalEntryFragment on JournalEntry {
3
+ id
4
+ accountId
5
+ type
6
+ notes
7
+ date
8
+ editAt
9
+
10
+ activity
11
+ item
12
+ quantity
13
+ unit
14
+ }`;
@@ -0,0 +1,24 @@
1
+
2
+ export const organizationFragment = `fragment organizationFragment on Organization {
3
+ id
4
+ stripeCustomerId
5
+ name
6
+ domains
7
+ }`;
8
+
9
+ export const organizationRelationshipFragment = `fragment organizationRelationshipFragment on OrganizationRelationship {
10
+ id
11
+ primary
12
+ role
13
+
14
+ acl {
15
+ id
16
+ billing
17
+ journal
18
+ members
19
+ finances
20
+ products
21
+ settings
22
+ integrations
23
+ }
24
+ }`;
@@ -1,4 +1,4 @@
1
- export const authFragment = `fragment authFragment on Auth {
1
+ export const userAuthFragment = `fragment userAuthFragment on Auth {
2
2
  token
3
3
  activated
4
4
  hasPassword
@@ -0,0 +1,53 @@
1
+ import { gql } from 'graphql-tag';
2
+ import { accountAuthFragment } from '../fragments/accountAuthFragments';
3
+ import { emailFragment, phoneFragment } from '../fragments/otherFragments';
4
+ import { accountFragment } from '../fragments/accountFragments';
5
+
6
+ const authenticateResultText = `...accountAuthFragment
7
+
8
+ account {
9
+ ...accountFragment
10
+
11
+ email {
12
+ ...emailFragment
13
+ }
14
+
15
+ phone {
16
+ ...phoneFragment
17
+ }
18
+ }`;
19
+
20
+ const authenticateFragments = `
21
+ ${accountAuthFragment}
22
+ ${accountFragment}
23
+ ${emailFragment}
24
+ ${phoneFragment}
25
+ `;
26
+
27
+ export const authenticateWithPasswordMtn = gql`
28
+ mutation authenticateWithPassword (
29
+ $identifier: String!
30
+ $password: String!
31
+ ) {
32
+ authenticateWithPassword (
33
+ identifier: $identifier,
34
+ password: $password
35
+ ) {
36
+ ${authenticateResultText}
37
+ }
38
+ }
39
+ ${authenticateFragments}
40
+ `;
41
+
42
+ export const authenticateWithTokenMtn = gql`
43
+ mutation authenticateWithToken (
44
+ $token: Token!
45
+ ) {
46
+ authenticateWithToken (
47
+ token: $token
48
+ ) {
49
+ ${authenticateResultText}
50
+ }
51
+ }
52
+ ${authenticateFragments}
53
+ `;
@@ -1,16 +1,54 @@
1
1
  import { gql } from 'graphql-tag';
2
- import { aiChatFragment } from '../fragments/aiChatFragments';
2
+ import { aiChatFragment, aiChatMessageFragment } from '../fragments/aiChatFragments';
3
3
 
4
4
  export const startAIChatMtn = gql`
5
5
  mutation startAIChat (
6
+ $organizationId: GenericID!
6
7
  $text: String!
7
8
  ) {
8
9
  startAIChat (
10
+ organizationId: $organizationId
9
11
  text: $text
10
12
  ) {
11
- ...aiChatFragment
13
+ sessionKey
14
+ node {
15
+ ...aiChatFragment
16
+ }
12
17
  }
13
18
  }
14
19
 
15
20
  ${aiChatFragment}
16
21
  `;
22
+
23
+ export const sendAIChatMessageMtn = gql`
24
+ mutation sendAIChatMessage (
25
+ $aiChatId: GenericID!
26
+ $organizationId: GenericID
27
+ $variablesKey: String
28
+ $text: String!
29
+ ) {
30
+ sendAIChatMessage (
31
+ aiChatId: $aiChatId
32
+ organizationId: $organizationId
33
+ variablesKey: $variablesKey
34
+ text: $text
35
+ ) {
36
+ sessionKey
37
+ node {
38
+ ...aiChatMessageFragment
39
+ }
40
+ }
41
+ }
42
+
43
+ ${aiChatMessageFragment}
44
+ `;
45
+
46
+ export const stopAIChatMessageMtn = gql`
47
+ mutation stopAIChatMessage (
48
+ $aiChatId: GenericID!
49
+ ) {
50
+ stopAIChatMessage (
51
+ aiChatId: $aiChatId
52
+ )
53
+ }
54
+ `;
@@ -0,0 +1,2 @@
1
+
2
+ // Insert journal mutations here
@@ -1,9 +1,9 @@
1
1
  import { gql } from 'graphql-tag';
2
+ import { userAuthFragment } from '../fragments/userAuthFragments';
2
3
  import { emailFragment, phoneFragment } from '../fragments/otherFragments';
3
4
  import { plusFragment, userFragment, userPersonaFragment } from '../fragments/userFragments';
4
- import { authFragment } from '../fragments/authFragments';
5
5
 
6
- const signInResultText = `...authFragment
6
+ const signInResultText = `...userAuthFragment
7
7
 
8
8
  user {
9
9
  ...userFragment
@@ -27,7 +27,7 @@ const signInResultText = `...authFragment
27
27
  }`;
28
28
 
29
29
  const signInFragments = `
30
- ${authFragment}
30
+ ${userAuthFragment}
31
31
  ${userFragment}
32
32
  ${plusFragment}
33
33
  ${emailFragment}
@@ -4,9 +4,7 @@ import { aiChatFragment, aiChatMessageFragment } from '../fragments/aiChatFragme
4
4
  export const aiChatQry = gql`
5
5
  query aiChat (
6
6
  $aiChatId: GenericID!
7
- $cursor: Cursor
8
- $after: Boolean!
9
- $limit: Int!
7
+ $limit: Int
10
8
  ) {
11
9
  aiChat (
12
10
  aiChatId: $aiChatId
@@ -14,11 +12,8 @@ query aiChat (
14
12
  ...aiChatFragment
15
13
 
16
14
  messages (
17
- cursor: $cursor
18
- after: $after
19
15
  limit: $limit
20
16
  ) {
21
- cursor
22
17
  ...aiChatMessageFragment
23
18
  }
24
19
  }
@@ -27,3 +22,44 @@ query aiChat (
27
22
  ${aiChatFragment}
28
23
  ${aiChatMessageFragment}
29
24
  `;
25
+
26
+ export const aiChatMessagesQry = gql`
27
+ query aiChatMessages (
28
+ $aiChatId: GenericID!
29
+ $cursor: Cursor
30
+ $after: Boolean!
31
+ $limit: Int!
32
+ ) {
33
+ aiChatMessages (
34
+ aiChatId: $aiChatId
35
+ cursor: $cursor
36
+ after: $after
37
+ limit: $limit
38
+ ) {
39
+ ...aiChatMessageFragment
40
+ }
41
+ }
42
+
43
+ ${aiChatMessageFragment}
44
+ `;
45
+
46
+ export const aiChatsQry = gql`
47
+ query aiChats (
48
+ $filter: AIChatsFilter
49
+ $cursor: Cursor
50
+ $after: Boolean!
51
+ $limit: Int!
52
+ ) {
53
+ aiChats (
54
+ filter: $filter
55
+ cursor: $cursor
56
+ after: $after
57
+ limit: $limit
58
+ ) {
59
+ cursor
60
+ ...aiChatFragment
61
+ }
62
+ }
63
+
64
+ ${aiChatFragment}
65
+ `;