@jsb188/graphql 1.1.3 → 1.1.5

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.
Files changed (39) hide show
  1. package/cache/config.ts +3 -3
  2. package/cache/index.ts +173 -85
  3. package/gql/fragments/accountAuthFragments.ts +3 -9
  4. package/gql/fragments/accountFragments.ts +11 -0
  5. package/gql/fragments/logFragments.ts +25 -0
  6. package/gql/fragments/organizationFragments.ts +10 -2
  7. package/gql/mutations/accountMutations.ts +21 -0
  8. package/gql/mutations/aiChatMutations.ts +1 -0
  9. package/gql/mutations/authMutations.ts +171 -0
  10. package/gql/mutations/index.ts +7 -0
  11. package/gql/mutations/logMutations.ts +43 -0
  12. package/gql/mutations/userAuthMutations.ts +0 -163
  13. package/gql/queries/aiChatQueries.ts +1 -0
  14. package/gql/queries/appQueries.ts +2 -1
  15. package/gql/queries/logQueries.ts +37 -0
  16. package/gql/queries/organizationQueries.ts +1 -0
  17. package/hooks/index.ts +134 -75
  18. package/hooks/use-account-mtn.ts +43 -0
  19. package/hooks/use-aiChat-mtn.ts +96 -0
  20. package/hooks/use-aiChat-qry.ts +65 -3
  21. package/hooks/use-auth-mtn.ts +99 -112
  22. package/hooks/use-log-mtn.ts +85 -0
  23. package/hooks/use-log-qry.ts +77 -0
  24. package/package.json +10 -20
  25. package/types.d.ts +1 -0
  26. package/gql/fragments/cardFragments.ts +0 -15
  27. package/gql/fragments/chatFragments.ts +0 -98
  28. package/gql/fragments/journalFragments.ts +0 -14
  29. package/gql/fragments/userAuthFragments.ts +0 -8
  30. package/gql/fragments/userFragments.ts +0 -69
  31. package/gql/mutations/accountAuthMutations.ts +0 -81
  32. package/gql/mutations/chatMutations.ts +0 -116
  33. package/gql/mutations/journalMutations.ts +0 -2
  34. package/gql/mutations/userMutations.ts +0 -89
  35. package/gql/queries/cardQueries.ts +0 -24
  36. package/gql/queries/chatQueries.ts +0 -86
  37. package/gql/queries/journalQueries.ts +0 -28
  38. package/gql/queries/userQueries.ts +0 -104
  39. package/hooks/use-journal-qry.ts +0 -50
package/hooks/index.ts CHANGED
@@ -7,8 +7,8 @@ import { useConnectedToServerValue, useFragmentObserverValue, useQueryObserverVa
7
7
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
8
8
  import { checkDataCompleteness, fetchCachedData, loadDataFromCache, loadFragment, makeVariablesKey, removeStaleCache } from '../cache';
9
9
  import { QUERY_EXPIRE_TIMES } from '../cache/config';
10
- import type { AnyModalPopUpFn, GraphQLHandlers, GraphQLQueryOptions, OnCompletedGQLFn, OnErrorGQLFn, UpdateDataObserverArgs, UpdateObserversFn } from '../types';
11
10
  import { graphqlRequest } from '../client/request';
11
+ import type { AnyModalPopUpFn, GraphQLHandlers, GraphQLQueryOptions, OnCompletedGQLFn, OnErrorGQLFn, UpdateDataObserverArgs, UpdateObserversFn } from '../types';
12
12
 
13
13
 
14
14
  /**
@@ -34,6 +34,7 @@ type GraphQLMutationResult = {
34
34
  variables: Record<string, any> | null;
35
35
  saving: boolean;
36
36
  error: ServerErrorObj | null;
37
+ mutationCount: number;
37
38
  };
38
39
 
39
40
  type GraphQLMutation = [
@@ -41,7 +42,7 @@ type GraphQLMutation = [
41
42
  GraphQLMutationResult,
42
43
  GraphQLHandlers,
43
44
  UpdateObserversFn,
44
- React.MutableRefObject<boolean>
45
+ React.MutableRefObject<Record<string, any>>
45
46
  ];
46
47
 
47
48
  /**
@@ -161,21 +162,48 @@ export function useWatchQuery(
161
162
  */
162
163
 
163
164
  export function useReactiveFragment(
164
- data_: any,
165
- observe: Array<string | string[]>,
166
- qryObsCount?: number,
165
+ data: any,
166
+ observe: Array<string | [string, string | null]>,
167
+ qryObsCount?: number | boolean,
167
168
  otherCheck?: (latestData: any, updatedKeys: any[]) => boolean,
168
169
  ignoreIDWarning?: boolean,
169
170
  // doTest?: boolean
170
171
  ) {
171
172
 
172
- const data = data_ || {};
173
173
  const fragmentObserver = useFragmentObserverValue();
174
174
  const frgObsCount = fragmentObserver.count;
175
- const [changedData, setChangedData] = useState<any>({
176
- fragmentUpdatedCount: frgObsCount,
177
- queryUpdatedCount: qryObsCount,
178
- data
175
+ const dataId = data?.id;
176
+
177
+ const [changedData, setChangedData] = useState<any>(() => {
178
+ // This allows initial data to *not* be null even when data param is null
179
+ let initialData = data;
180
+
181
+ observe.forEach((key) => {
182
+ const isMapped = Array.isArray(key);
183
+ const fragmentData = loadFragment(isMapped ? key[0] : key);
184
+
185
+ if (fragmentData) {
186
+ if (isMapped) {
187
+ if (key[1]) {
188
+ initialData = {
189
+ ...initialData!,
190
+ [key[1]]: fragmentData,
191
+ };
192
+ }
193
+ } else {
194
+ initialData = {
195
+ ...initialData!,
196
+ ...fragmentData,
197
+ };
198
+ }
199
+ }
200
+ });
201
+
202
+ return {
203
+ fragmentUpdatedCount: frgObsCount,
204
+ queryUpdatedCount: qryObsCount,
205
+ data: initialData
206
+ };
179
207
  });
180
208
 
181
209
  if (getENVVariable('NODE_ENV') === 'development' && !ignoreIDWarning) {
@@ -184,21 +212,22 @@ export function useReactiveFragment(
184
212
  useEffect(() => {
185
213
  if (
186
214
  // getENVVariable('NODE_ENV') === 'development' &&
187
- data.id && changedData.data?.id &&
188
- data.id !== changedData.data?.id
215
+ dataId && changedData.data?.id &&
216
+ dataId !== changedData.data?.id
189
217
  ) {
190
- console.warn(`WARNING: useReactiveFragment() data.id changed from ${data.id} to ${changedData.data?.id}`);
218
+ console.warn(`WARNING: useReactiveFragment() data.id changed from ${dataId} to ${changedData.data?.id}`);
191
219
  console.warn('This can result in invalid merged data. Use key={id} to avoid this error.');
192
220
  }
193
221
  }, [changedData.data?.id]);
194
222
  }
195
223
 
196
224
  useEffect(() => {
197
- // NOTE: I tried this with effect()
225
+ // NOTE: I tried this with Preact's effect()
198
226
  // But that caused the render to happen 3 times more, I don't know why.
199
227
  // I only solved it by using useEffect()
200
228
  const idsChanged = (
201
- changedData.data.id !== data.id ||
229
+ !dataId ||
230
+ changedData.data.id !== dataId ||
202
231
  (
203
232
  // This is absolutely needed for the chat clientId system to work properly;
204
233
  // Otherwise messages will be stuck in "not sent" state.
@@ -220,48 +249,52 @@ export function useReactiveFragment(
220
249
  )
221
250
  ) {
222
251
 
223
- // if (doTest) {
224
- // console.log('DO TEST:');
225
- // console.log(observe);
226
- // console.log(fragmentObserver);
227
- // }
252
+ const dataUpdated = (
253
+ idsChanged ||
254
+ forceReactive ||
255
+ observe.some((key) => {
256
+ const isMapped = Array.isArray(key);
257
+ return isMapped ? fragmentObserver.list.includes(key[0]) : fragmentObserver.list.includes(key);
258
+ })
259
+ )
228
260
 
229
261
  let newData;
230
- for (const key of observe) {
231
- const isMapped = Array.isArray(key);
232
- if (
233
- key && (
234
- idsChanged ||
235
- forceReactive ||
236
- (isMapped && fragmentObserver.list.includes(key[0])) ||
237
- (!isMapped && fragmentObserver.list.includes(key))
238
- )
239
- ) {
240
- if (!newData) {
241
- if (idsChanged) {
242
- newData = data;
243
- } else if (data) {
244
- newData = {
245
- ...data,
246
- ...changedData.data,
247
- };
248
- } else {
249
- newData = changedData.data;
262
+ if (dataUpdated) {
263
+ for (const key of observe) {
264
+ const isMapped = Array.isArray(key);
265
+
266
+ if (key) {
267
+ if (!newData) {
268
+ if (idsChanged) {
269
+ newData = data;
270
+ } else if (data) {
271
+ newData = {
272
+ ...data,
273
+ ...changedData.data,
274
+ };
275
+ } else {
276
+ newData = changedData.data;
277
+ }
250
278
  }
251
- }
252
279
 
253
- const fragmentData = loadFragment(isMapped ? key[0] : key);
254
- if (fragmentData) {
255
- if (isMapped) {
256
- newData = {
257
- ...newData,
258
- [key[1]]: fragmentData,
259
- };
260
- } else {
261
- newData = {
262
- ...newData,
263
- ...fragmentData,
264
- };
280
+ const fragmentData = loadFragment(isMapped ? key[0] : key);
281
+ // console.log('fragmentKey', key);
282
+ // console.log('fragmentData', fragmentData);
283
+
284
+ if (fragmentData) {
285
+ if (isMapped) {
286
+ if (key[1]) {
287
+ newData = {
288
+ ...newData,
289
+ [key[1]]: fragmentData,
290
+ };
291
+ }
292
+ } else {
293
+ newData = {
294
+ ...newData,
295
+ ...fragmentData,
296
+ };
297
+ }
265
298
  }
266
299
  }
267
300
  }
@@ -275,7 +308,7 @@ export function useReactiveFragment(
275
308
  });
276
309
  }
277
310
  }
278
- }, [data.id, qryObsCount, frgObsCount]);
311
+ }, [dataId, qryObsCount, frgObsCount]);
279
312
 
280
313
  // This is not needed now, I think
281
314
  // useEffect(() => {
@@ -384,19 +417,27 @@ export function useMutation(
384
417
  // But bring it back if you want ability to "cancel"
385
418
  // const controller = useRef();
386
419
 
387
- const mounted = useRef(true);
420
+ const tracker = useRef({
421
+ mounted: true,
422
+ timer: null as NodeJS.Timeout | null,
423
+ });
424
+
388
425
  const [mtnValues, setMtnValues] = useState({
389
426
  variables: null as Record<string, any> | null,
390
427
  saving: false,
391
428
  data: null,
392
- error: initialError || null as ServerErrorObj | null
429
+ error: initialError || null as ServerErrorObj | null,
430
+ mutationCount: 0,
393
431
  });
394
432
 
395
433
  // Mounted hook
396
434
 
397
435
  useEffect(() => {
398
436
  return () => {
399
- mounted.current = false;
437
+ tracker.current.mounted = false;
438
+ if (tracker.current.timer) {
439
+ clearTimeout(tracker.current.timer);
440
+ }
400
441
  };
401
442
  }, []);
402
443
 
@@ -429,9 +470,10 @@ export function useMutation(
429
470
  {
430
471
  openModalPopUp: retryCount >= triedCount ? openModalPopUp : null,
431
472
  onCompleted: (data: any | null, error: ServerErrorObj | null) => {
432
- if (mounted.current) {
473
+ if (tracker.current.mounted) {
433
474
  setMtnValues({
434
475
  ...mtnValues,
476
+ mutationCount: mtnValues.mutationCount + 1,
435
477
  saving: false,
436
478
  data: data.data || null,
437
479
  error,
@@ -439,14 +481,14 @@ export function useMutation(
439
481
  }
440
482
 
441
483
  if (data.data) {
442
- if (onCompleted && (mounted.current || !checkMountedBeforeCallback)) {
484
+ if (onCompleted && (tracker.current.mounted || !checkMountedBeforeCallback)) {
443
485
  // Do separate {mounted.current} check from outside
444
486
  onCompleted(data.data, error, graphqlOptions?.variables);
445
487
  }
446
488
  }
447
489
  },
448
490
  onError: (error: ServerErrorObj | null) => {
449
- if (mounted.current) {
491
+ if (tracker.current.mounted) {
450
492
  setMtnValues({
451
493
  ...mtnValues,
452
494
  saving: retryCount > triedCount,
@@ -454,7 +496,7 @@ export function useMutation(
454
496
  });
455
497
  }
456
498
 
457
- if (onError && retryCount <= triedCount && (mounted.current || !checkMountedBeforeCallback)) {
499
+ if (onError && retryCount <= triedCount && (tracker.current.mounted || !checkMountedBeforeCallback)) {
458
500
  onError(error, graphqlOptions?.variables);
459
501
  }
460
502
  },
@@ -486,37 +528,48 @@ export function useMutation(
486
528
  };
487
529
 
488
530
  const mtnHandlers: GraphQLHandlers = {
489
- resetErrors: function () {
531
+ resetErrors: () => {
490
532
  setMtnValues({
491
533
  ...mtnValues,
492
534
  error: null,
493
535
  });
494
536
  },
495
- setError: function (errorObj: SimpleErrorType) {
537
+ setError: (errorObj: SimpleErrorType) => {
496
538
  setMtnValues({
497
539
  ...mtnValues,
498
540
  error: {
499
- ...errorObj,
500
541
  statusCode: 200,
501
542
  errorCode: 'custom_error',
543
+ ...errorObj,
502
544
  },
503
545
  });
504
546
  },
505
- refetch: function () {
547
+ refetch: () => {
506
548
  const lastVariables = mtnValues.variables;
507
549
  return doMutate(lastVariables ? { variables: lastVariables } : undefined);
508
550
  },
551
+ setSaving: (nextSaving: boolean, resetInMS?: number) => {
552
+ setMtnValues({
553
+ ...mtnValues,
554
+ saving: nextSaving,
555
+ });
556
+
557
+ if (nextSaving && resetInMS) {
558
+ if (tracker.current.timer) {
559
+ clearTimeout(tracker.current.timer);
560
+ }
561
+
562
+ tracker.current.timer = setTimeout(() => {
563
+ setMtnValues({
564
+ ...mtnValues,
565
+ saving: false,
566
+ });
567
+ }, resetInMS);
568
+ }
569
+ }
509
570
  };
510
571
 
511
- // useEffect(() => {
512
- // return () => {
513
- // if (controller.current) {
514
- // controller.current.abort();
515
- // }
516
- // };
517
- // }, []);
518
-
519
- return [doMutate, mtnValues, mtnHandlers, updateObservers, mounted];
572
+ return [doMutate, mtnValues, mtnHandlers, updateObservers, tracker];
520
573
  }
521
574
 
522
575
  /**
@@ -673,7 +726,12 @@ export function useQuery(
673
726
 
674
727
  return () => {
675
728
  unsetQueryTracker(queryKey, tracker.current.unique);
729
+ };
730
+ }, [queryKey]);
731
+
676
732
 
733
+ useEffect(() => {
734
+ return () => {
677
735
  if (tracker.current.abortCtrl) {
678
736
  // console.log('UMOUNTED:', queryKey, tracker.current.unique);
679
737
  tracker.current.abortCtrl.abort({
@@ -682,7 +740,7 @@ export function useQuery(
682
740
  });
683
741
  }
684
742
  };
685
- }, [queryKey]);
743
+ }, []);
686
744
 
687
745
  // Refetch when variables, skip status or query observer changes
688
746
 
@@ -695,6 +753,7 @@ export function useQuery(
695
753
  )
696
754
  ) {
697
755
  const cachedResult = fetchCachedData(query, variablesKey, updateObservers);
756
+
698
757
  if (cachedResult) {
699
758
  setQryValues({
700
759
  ...qryValues,
@@ -0,0 +1,43 @@
1
+ import type { UseMutationParams } from '@jsb188/graphql/types.d';
2
+ import { OpenModalPopUpFn, useCurrentAccount } from '@jsb188/react/states';
3
+ import { editAccountMtn } from '../gql/mutations/accountMutations';
4
+ import { useMutation } from './index';
5
+
6
+ /**
7
+ * Edit logged in user's account
8
+ */
9
+
10
+ export function useEditAccount(
11
+ params?: UseMutationParams | null,
12
+ openModalPopUp?: OpenModalPopUpFn
13
+ ) {
14
+
15
+ const { account, settings, dispatchApp } = useCurrentAccount();
16
+ const [editAccount, mtnValues, mtnHandlers] = useMutation(
17
+ editAccountMtn,
18
+ {
19
+ // checkMountedBeforeCallback: true,
20
+ openModalPopUp,
21
+ ...params,
22
+ onCompleted: (data, error) => {
23
+ params?.onCompleted?.(data, error);
24
+
25
+ const updatedData = data.editAccount;
26
+ if (updatedData) {
27
+ dispatchApp({
28
+ __type: 'APP_EDIT_ACCOUNT',
29
+ data: updatedData,
30
+ });
31
+ }
32
+ }
33
+ },
34
+ );
35
+
36
+ return {
37
+ account,
38
+ settings,
39
+ editAccount,
40
+ ...mtnValues,
41
+ ...mtnHandlers,
42
+ };
43
+ }
@@ -0,0 +1,96 @@
1
+ import { updateQuery } from '../cache/';
2
+ import { useMutation } from '../client';
3
+ import { updateAIChats } from './use-aiChat-qry';
4
+ import { sendAIChatMessageMtn, startAIChatMtn, stopAIChatMessageMtn } from '../gql/mutations/aiChatMutations';
5
+ import type { UseMutationParams } from '../types.d';
6
+ import { useOpenModalPopUp } from '@jsb188/react/states';
7
+
8
+ /**
9
+ * Start AI chat
10
+ */
11
+
12
+ export function useStartAIChat(params: UseMutationParams = {}) {
13
+
14
+ const { onCompleted, onError } = params;
15
+ const openModalPopUp = useOpenModalPopUp();
16
+
17
+ const [startAIChat, mtnValues,, updateObservers] = useMutation(
18
+ startAIChatMtn,
19
+ {
20
+ openModalPopUp,
21
+ onCompleted: (data: any, err: any, variables: any) => {
22
+ onCompleted?.(data, err, variables);
23
+
24
+ const aiChat = data.startAIChat?.node;
25
+ updateAIChats(aiChat, updateObservers);
26
+ },
27
+ onError,
28
+ },
29
+ );
30
+
31
+ return {
32
+ startAIChat,
33
+ ...mtnValues,
34
+ };
35
+ }
36
+
37
+ /**
38
+ * Send a new message to AI Chat
39
+ */
40
+
41
+ export function useAIChatTextarea(variablesKey: string, params: UseMutationParams = {}) {
42
+
43
+ const { onCompleted, onError } = params;
44
+ const openModalPopUp = useOpenModalPopUp();
45
+
46
+ // Send AI chat message
47
+
48
+ const [sendAIChatMessage, mtnValues1,, updateObservers] = useMutation(
49
+ sendAIChatMessageMtn,
50
+ {
51
+ openModalPopUp,
52
+ onCompleted: (data: any, err: any, variables: any) => {
53
+ onCompleted?.(data, err, variables);
54
+
55
+ const aiChatId = variables.aiChatId;
56
+ const messageId = data.sendAIChatMessage?.node?.id;
57
+
58
+ if (messageId && aiChatId && variablesKey) {
59
+ updateQuery(`#aiChat:${variablesKey}`, (currentData: any) => {
60
+ if (Array.isArray(currentData.messages?.data)) {
61
+ currentData.messages.data.push([`$aiChatMessageFragment:${messageId}`]);
62
+ }
63
+ return currentData;
64
+ }, false, updateObservers);
65
+ } else if (data && !err) {
66
+ console.dev(`Unknown error: {${messageId ? 'aiChatId' : 'messageId'}} was not found.`, 'warning');
67
+ }
68
+ },
69
+ onError,
70
+ },
71
+ );
72
+
73
+ // Stop AI chat message
74
+
75
+ const [stopAIChatMessage, mtnValues2] = useMutation(
76
+ stopAIChatMessageMtn,
77
+ {
78
+ openModalPopUp,
79
+ onCompleted: (data: any, err: any, variables: any) => {
80
+ onCompleted?.(data, err, variables);
81
+ },
82
+ onError,
83
+ },
84
+ );
85
+
86
+ return {
87
+ send: {
88
+ sendAIChatMessage,
89
+ ...mtnValues1,
90
+ },
91
+ stop: {
92
+ stopAIChatMessage,
93
+ ...mtnValues2,
94
+ }
95
+ };
96
+ }
@@ -2,11 +2,11 @@ import { getENVVariable } from '@jsb188/app';
2
2
  import { getAuthToken } from '@jsb188/app/utils/api';
3
3
  import SSE from '@jsb188/sse';
4
4
  import { useEffect, useState } from 'react';
5
- import { loadFragment } from '../cache/';
5
+ import { loadFragment, loadQuery, makeVariablesKey, updateQuery } from '../cache/';
6
6
  import { useQuery } from '../client';
7
7
  import { aiChatMessagesQry, aiChatQry, aiChatsQry } from '../gql/queries/aiChatQueries';
8
8
  import handleSSEData, { type PublishPayload } from '../sse';
9
- import type { UseQueryParams } from '../types.d';
9
+ import type { UpdateObserversFn, UseQueryParams } from '../types.d';
10
10
 
11
11
  /**
12
12
  * Constants
@@ -105,6 +105,39 @@ export function useAIChatWithSSE(aiChatId?: string, initialSessionKey?: string |
105
105
  }
106
106
  }, [dataAIChatId, sessionKey]);
107
107
 
108
+ useEffect(() => {
109
+ // Every time AIChat is fetched, check if it exists in lists cache
110
+ if (dataAIChatId) {
111
+ const variablesKey = makeVariablesKey({
112
+ filter: aiChat.calDate ? 'CAL_DATE' : 'CHATS',
113
+ cursor: null,
114
+ after: false,
115
+ limit: AI_CHATS_LIMIT
116
+ });
117
+
118
+ const queryKey = `#aiChats:${variablesKey}`;
119
+ const queryCache = loadQuery(queryKey);
120
+
121
+ if (queryCache) {
122
+ const notFound = queryCache.every((a: any) => a.id !== dataAIChatId);
123
+
124
+ if (notFound) {
125
+ // If not found, add to cache
126
+ updateQuery(queryKey, (prev: any) => {
127
+ return [{
128
+ cursor: aiChat.cursor,
129
+ __flat: {
130
+ __cache: true,
131
+ data: [`$aiChatFragment:${dataAIChatId}`],
132
+ }
133
+ }, ...prev];
134
+ }, false, updateObservers);
135
+ }
136
+ }
137
+
138
+ }
139
+ }, [dataAIChatId]);
140
+
108
141
  return {
109
142
  aiChat,
110
143
  generatingFragmentId,
@@ -138,11 +171,40 @@ export function useAIChatMessages(aiChatId?: string, params: UseQueryParams = {}
138
171
  };
139
172
  }
140
173
 
174
+ /**
175
+ * Update sidebar AI chats query
176
+ */
177
+
178
+ export function updateAIChats(aiChat: any, updateObservers: UpdateObserversFn) {
179
+ if (aiChat) {
180
+ const isCalDate = !!aiChat.calDate;
181
+ const queryKey = `#aiChats:$after:false$filter:${isCalDate ? 'cal_date' : 'chats'}$limit:${AI_CHATS_LIMIT}`;
182
+
183
+ updateQuery(
184
+ queryKey,
185
+ (res) => {
186
+ return [
187
+ {
188
+ cursor: aiChat.cursor,
189
+ __flat: {
190
+ __cache: true,
191
+ data: [`$aiChatFragment:${aiChat.id}`]
192
+ }
193
+ },
194
+ ...res
195
+ ];
196
+ },
197
+ false,
198
+ updateObservers
199
+ );
200
+ }
201
+ }
202
+
141
203
  /**
142
204
  * Fetch AI chats list
143
205
  */
144
206
 
145
- export function useAIChats(filter?: 'CAL_DATE') {
207
+ export function useAIChats(filter?: 'CAL_DATE' | 'CHATS') {
146
208
  const { data, ...other } = useQuery(aiChatsQry, {
147
209
  variables: {
148
210
  filter,