@jsb188/graphql 1.0.4 → 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
@@ -19,6 +19,7 @@ export const RULES = {
19
19
  // List of queries that should be cached
20
20
  // NOTE: Fragments are always cached
21
21
  aiChat: true,
22
+ aiChatMessages: true,
22
23
  alerts: true,
23
24
  cardsForUser: true,
24
25
  chat: true,
@@ -35,7 +36,8 @@ export const RULES = {
35
36
 
36
37
  // All fragments are cached,
37
38
  // but if you want to skip some, add it here
38
- authFragment: false,
39
+ accountAuthFragment: false,
40
+ userAuthFragment: false,
39
41
  } as {
40
42
  __limit: number;
41
43
  [key: string]: boolean | number;
package/cache/index.ts CHANGED
@@ -116,6 +116,7 @@ function extractFragment(dataObj: any, innerSelection: any[]) {
116
116
 
117
117
  export function loadQuery(queryKey: string, referencesOnly?: boolean) {
118
118
  const references = QUERIES.get(queryKey);
119
+
119
120
  if (referencesOnly) {
120
121
  return references;
121
122
  } else if (!references) {
@@ -301,7 +302,7 @@ function makeCacheObject(data: any, selections: any[], variables?: any, cacheMap
301
302
  */
302
303
 
303
304
  function saveQueryToMemory(
304
- requestData: any | null,
305
+ requestData: any,
305
306
  selection: any,
306
307
  variables: any,
307
308
  variablesKey: string,
package/client/index.ts CHANGED
@@ -1,2 +1,2 @@
1
- export * from './hooks';
1
+ export * from '../hooks/index';
2
2
  export * from './request';
package/client/request.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { getENVVariable } from '@jsb188/app';
2
- import type { ServerErrorObj } from '@jsb188/app/types/app';
2
+ import type { ServerErrorObj } from '@jsb188/app/types/app.d';
3
3
  import { getAuthToken, normalizeServerError } from '@jsb188/app/utils/api';
4
4
  import { delay } from '@jsb188/app/utils/logic';
5
5
  import { setDataToCache } from '../cache/';
@@ -12,6 +12,7 @@ import { apiRequestHeaders, isServerErrorGQL } from '../utils';
12
12
 
13
13
  type GraphQLMutationOptions = Partial<{
14
14
  authToken: string;
15
+ ipAddress: string | null; // Only used if SSR
15
16
  retryCount: number;
16
17
  variables: any;
17
18
  cacheMap: any;
@@ -121,24 +122,24 @@ export async function graphqlRequest(
121
122
  updateObservers?: UpdateObserversFn,
122
123
  ): Promise<any> {
123
124
 
124
- const { openModalPopUp, onCompleted, onError, authToken, cacheMap } = params || {};
125
+ const { openModalPopUp, onCompleted, onError, authToken, cacheMap, ipAddress } = params || {};
125
126
 
126
127
  if (!gqlQuery?.definitions) {
127
128
  console.log(gqlQuery);
128
129
  }
129
130
 
130
131
  const operationName = gqlQuery?.definitions?.find((def: any) => def.kind === 'OperationDefinition')?.name?.value;
131
- const headers = apiRequestHeaders(getENVVariable('IS_BROWSER') ? getAuthToken() : authToken);
132
+ const headers = apiRequestHeaders(getENVVariable('IS_BROWSER') ? getAuthToken() : authToken, ipAddress);
132
133
 
133
134
  // Use this to check queries that are getting double-requested
134
135
  // doLog(gqlQuery, 'QUERYING... $0');
135
136
 
136
- return fetch(getENVVariable('GQL_SERVER')!, {
137
+ return fetch(getENVVariable('GQL_SERVER') as string, {
137
138
  signal: controllerSignal,
138
139
  method: 'POST',
139
140
  // credentials: 'same-origin',
140
141
  // headers: new Headers({
141
- headers: new Headers(headers),
142
+ headers,
142
143
  // headers,
143
144
  body: JSON.stringify({
144
145
  query: gqlQuery?.loc?.source.body,
@@ -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,13 +4,16 @@ import { aiChatFragment, aiChatMessageFragment } from '../fragments/aiChatFragme
4
4
  export const aiChatQry = gql`
5
5
  query aiChat (
6
6
  $aiChatId: GenericID!
7
+ $limit: Int
7
8
  ) {
8
9
  aiChat (
9
10
  aiChatId: $aiChatId
10
11
  ) {
11
12
  ...aiChatFragment
12
13
 
13
- messages {
14
+ messages (
15
+ limit: $limit
16
+ ) {
14
17
  ...aiChatMessageFragment
15
18
  }
16
19
  }
@@ -39,3 +42,24 @@ query aiChatMessages (
39
42
 
40
43
  ${aiChatMessageFragment}
41
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
+ `;
@@ -0,0 +1,22 @@
1
+ import { gql } from 'graphql-tag';
2
+ import { journalEntryFragment } from '../fragments/journalFragments';
3
+
4
+ export const journalEntriesQry = gql`
5
+ query journalEntries (
6
+ $organizationId: GenericID!
7
+ $cursor: Cursor
8
+ $after: Boolean!
9
+ $limit: Int!
10
+ ) {
11
+ journalEntries (
12
+ organizationId: $organizationId
13
+ cursor: $cursor
14
+ after: $after
15
+ limit: $limit
16
+ ) {
17
+ ...journalEntryFragment
18
+ }
19
+ }
20
+
21
+ ${journalEntryFragment}
22
+ `;
@@ -0,0 +1,52 @@
1
+ import { gql } from 'graphql-tag';
2
+ import { organizationFragment, organizationRelationshipFragment } from '../fragments/organizationFragments';
3
+
4
+ // Always use organizationRelationship() instead
5
+
6
+ // export const organizationQry = gql`
7
+ // query organization (
8
+ // $organizationId: GenericID!
9
+ // ) {
10
+ // organization (
11
+ // organizationId: $organizationId
12
+ // ) {
13
+ // ...organizationFragment
14
+ // }
15
+ // }
16
+
17
+ // ${organizationFragment}
18
+ // `;
19
+
20
+ export const organizationRelationshipQry = gql`
21
+ query organizationRelationship (
22
+ $organizationId: GenericID!
23
+ ) {
24
+ organizationRelationship (
25
+ organizationId: $organizationId
26
+ ) {
27
+ ...organizationRelationshipFragment
28
+
29
+ organization {
30
+ ...organizationFragment
31
+ }
32
+ }
33
+ }
34
+
35
+ ${organizationFragment}
36
+ ${organizationRelationshipFragment}
37
+ `;
38
+
39
+ export const myOrganizationsQry = gql`
40
+ query myOrganizations {
41
+ myOrganizations {
42
+ ...organizationRelationshipFragment
43
+
44
+ organization {
45
+ ...organizationFragment
46
+ }
47
+ }
48
+ }
49
+
50
+ ${organizationFragment}
51
+ ${organizationRelationshipFragment}
52
+ `;
@@ -1,19 +1,22 @@
1
1
  import { getENVVariable } from '@jsb188/app';
2
- import type { ServerErrorObj, SimpleErrorType } from '@jsb188/app/types/app';
2
+ import type { ServerErrorObj, SimpleErrorType } from '@jsb188/app/types/app.d';
3
+ import { normalizeServerError } from '@jsb188/app/utils/api';
3
4
  import { delay } from '@jsb188/app/utils/logic';
4
5
  import { isServerErrorGQL } from '@jsb188/graphql/utils';
5
6
  import { useConnectedToServerValue, useFragmentObserverValue, useQueryObserverValue, useScreenIsFocusedValue, useSetFragmentObserver, useSetQueryObserver } from '@jsb188/react/states';
6
7
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
7
- import { checkDataCompleteness, fetchCachedData, loadDataFromCache, loadFragment, makeVariablesKey, removeStaleCache } from '../cache/';
8
+ import { checkDataCompleteness, fetchCachedData, loadDataFromCache, loadFragment, makeVariablesKey, removeStaleCache } from '../cache';
8
9
  import { QUERY_EXPIRE_TIMES } from '../cache/config';
9
- import type { AnyModalPopUpFn, GraphQLHandlers, GraphQLQueryOptions, OnCompletedGQLFn, OnErrorGQLFn, UpdateDataObserverArgs, UpdateObserversFn } from '../types.d';
10
- import { graphqlRequest } from './request';
10
+ import type { AnyModalPopUpFn, GraphQLHandlers, GraphQLQueryOptions, OnCompletedGQLFn, OnErrorGQLFn, UpdateDataObserverArgs, UpdateObserversFn } from '../types';
11
+ import { graphqlRequest } from '../client/request';
11
12
 
12
13
 
13
14
  /**
14
15
  * Types; mutation
15
16
  */
16
17
 
18
+ export type GraphQLMutationFn = (graphqlOptions?: GraphQLRequestOptions, triedCount?: number) => Promise<any>;
19
+
17
20
  type GraphQLMutationOptions = Partial<{
18
21
  checkMountedBeforeCallback: boolean;
19
22
  authToken: string;
@@ -34,7 +37,7 @@ type GraphQLMutationResult = {
34
37
  };
35
38
 
36
39
  type GraphQLMutation = [
37
- (graphqlOptions?: GraphQLRequestOptions, triedCount?: number) => Promise<any>,
40
+ GraphQLMutationFn,
38
41
  GraphQLMutationResult,
39
42
  GraphQLHandlers,
40
43
  UpdateObserversFn,
@@ -56,6 +59,8 @@ type GraphQLQueryResult = {
56
59
  error: ServerErrorObj | null;
57
60
  refetch: () => void;
58
61
  fetchMore: (obj: GraphQLRequestOptions) => Promise<any>;
62
+ queryName: string;
63
+ queryKey: string;
59
64
  variablesKey: string;
60
65
  updatedCount: number;
61
66
  updateObservers: UpdateObserversFn;
@@ -533,7 +538,7 @@ export function useQuery(
533
538
  // Multiple queries can be chained using this hook,
534
539
  // but only the first query is used for tracking reactivity.
535
540
  const queryName = query.definitions?.[0]?.name?.value;
536
- const queryKey = queryName + ':' + variablesKey;
541
+ const queryKey = `#${queryName}:${variablesKey}`;
537
542
 
538
543
  const tracker = useRef({
539
544
  unique: null as string | null,
@@ -751,8 +756,17 @@ export function useQuery(
751
756
  return doQuery();
752
757
  }, [doQuery]);
753
758
 
754
- const fetchMore = useCallback((obj: GraphQLRequestOptions): Promise<any> => {
755
- return doQuery(obj?.variables);
759
+ const fetchMore = useCallback(async(obj: GraphQLRequestOptions): Promise<any> => {
760
+ const result = await doQuery(obj?.variables);
761
+
762
+ if (result.error) {
763
+ return {
764
+ ...result,
765
+ error: normalizeServerError(result.error),
766
+ };
767
+ }
768
+
769
+ return result;
756
770
  }, [doQuery]);
757
771
 
758
772
  return {
@@ -764,6 +778,8 @@ export function useQuery(
764
778
  cacheMap,
765
779
  eagerFragmentKeyMap,
766
780
  ),
781
+ queryName,
782
+ queryKey,
767
783
  variablesKey,
768
784
  refetch,
769
785
  fetchMore,
@@ -0,0 +1,160 @@
1
+ import { getENVVariable } from '@jsb188/app';
2
+ import { getAuthToken } from '@jsb188/app/utils/api';
3
+ import SSE from '@jsb188/sse';
4
+ import { useEffect, useState } from 'react';
5
+ import { loadFragment } from '../cache/';
6
+ import { useQuery } from '../client';
7
+ import { aiChatMessagesQry, aiChatQry, aiChatsQry } from '../gql/queries/aiChatQueries';
8
+ import handleSSEData, { type PublishPayload } from '../sse';
9
+ import type { UseQueryParams } from '../types.d';
10
+
11
+ /**
12
+ * Constants
13
+ */
14
+
15
+ const AI_CHATS_LIMIT = 100; // Must match server code exactly
16
+ const AI_CHAT_MESSAGES_LIMIT = 100; // Must match server code exactly
17
+
18
+ /**
19
+ * Helper; get generating (status) key from SSE data
20
+ */
21
+
22
+ function getGeneratingFragmentId(sseData: PublishPayload) {
23
+ const { __type, dataFragmentKey, fragmentKey, fragmentNamespace, data } = sseData;
24
+ const finished = data?.finished;
25
+
26
+ if (__type === 'CONNECTED') {
27
+ return null;
28
+ }
29
+
30
+ const fragmentName = '$aiChatMessageFragment:';
31
+
32
+ if (typeof finished === 'boolean') {
33
+ if (dataFragmentKey?.startsWith(fragmentName) ) {
34
+ return finished ? null : dataFragmentKey;
35
+ } else if (fragmentKey?.startsWith(fragmentName)) {
36
+ return finished ? null : fragmentKey;
37
+ }
38
+ } else if (
39
+ fragmentKey?.startsWith(fragmentName) &&
40
+ fragmentNamespace === 'text'
41
+ ) {
42
+ return fragmentKey;
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Fetch AI chat
48
+ */
49
+
50
+ export function useAIChatWithSSE(aiChatId?: string, initialSessionKey?: string | null, params: UseQueryParams = {}) {
51
+
52
+ const { data, ...other } = useQuery(aiChatQry, {
53
+ variables: {
54
+ aiChatId
55
+ },
56
+ skip: !aiChatId,
57
+ ...params,
58
+ });
59
+
60
+ const { updateObservers } = other;
61
+ const [sessionKey, setSessionKey] = useState<string | null>(initialSessionKey || null);
62
+ const [generatingFragmentId, setGeneratingFragmentId] = useState<string | null>(null);
63
+ const aiChat = data?.aiChat || loadFragment(`$aiChatFragment:${aiChatId}`);
64
+ const dataAIChatId = aiChat?.id;
65
+
66
+ useEffect(() => {
67
+ // Browser has too many issues such as proxy, network, roadblocks
68
+ // that make it unreliable to use perpetual SSE in production.
69
+ // So we have to write the logic to make it work without perpetual session.
70
+
71
+ if (dataAIChatId && sessionKey) {
72
+ // Only listen to events if data is loaded
73
+ const connection = new SSE({
74
+ host: getENVVariable('SSE_SERVER') as string,
75
+ path: `page_events/ai_chat/${dataAIChatId}`,
76
+ // path: 'test-sse',
77
+ searchParams: {
78
+ session_key: sessionKey,
79
+ auth_token: getAuthToken()
80
+ }
81
+ });
82
+
83
+ const connectParams = {
84
+ onMessage: (sseData: PublishPayload) => {
85
+ handleSSEData(sseData, updateObservers);
86
+
87
+ const nextValue = getGeneratingFragmentId(sseData);
88
+ if (nextValue === null || typeof nextValue === 'string') {
89
+ setGeneratingFragmentId(nextValue);
90
+ }
91
+ },
92
+ onError: () => {
93
+ setGeneratingFragmentId(null);
94
+ }
95
+ };
96
+
97
+ connection.connect(connectParams);
98
+
99
+ // const removeNetworkListeners = reconnectOnBrowserNetwork(connection, connectParams);
100
+
101
+ return () => {
102
+ connection.close();
103
+ // removeNetworkListeners();
104
+ };
105
+ }
106
+ }, [dataAIChatId, sessionKey]);
107
+
108
+ return {
109
+ aiChat,
110
+ generatingFragmentId,
111
+ sessionKey,
112
+ setSessionKey,
113
+ ...other
114
+ };
115
+ }
116
+
117
+ /**
118
+ * Fetch AI chat messages
119
+ */
120
+
121
+ export function useAIChatMessages(aiChatId?: string, params: UseQueryParams = {}) {
122
+
123
+ const { data, ...other } = useQuery(aiChatMessagesQry, {
124
+ variables: {
125
+ aiChatId,
126
+ cursor: null,
127
+ after: true,
128
+ limit: AI_CHAT_MESSAGES_LIMIT
129
+ },
130
+ // If this query is used for virtualized list pagination, set {params.skip=true}
131
+ skip: !aiChatId,
132
+ ...params,
133
+ });
134
+
135
+ return {
136
+ aiChatMessages: data?.aiChatMessages,
137
+ ...other
138
+ };
139
+ }
140
+
141
+ /**
142
+ * Fetch AI chats list
143
+ */
144
+
145
+ export function useAIChats(filter?: 'CAL_DATE') {
146
+ const { data, ...other } = useQuery(aiChatsQry, {
147
+ variables: {
148
+ filter,
149
+ cursor: null,
150
+ after: false,
151
+ limit: AI_CHATS_LIMIT
152
+ },
153
+ skip: false,
154
+ });
155
+
156
+ return {
157
+ aiChats: data?.aiChats,
158
+ ...other
159
+ };
160
+ }
@@ -0,0 +1,19 @@
1
+ import { useQuery } from '@jsb188/graphql/client';
2
+ import { updateNoteQry } from '../gql/queries/appQueries';
3
+ import type { UseQueryParams } from '../types.d';
4
+
5
+ /**
6
+ * Fetch update notes
7
+ */
8
+
9
+ export function useUpdateNote(accountId?: string | null, params: UseQueryParams = {}) {
10
+ const { data, ...other } = useQuery(updateNoteQry, {
11
+ skip: !accountId,
12
+ ...params,
13
+ });
14
+
15
+ return {
16
+ updateNote: data?.updateNote,
17
+ ...other
18
+ };
19
+ }
@@ -0,0 +1,234 @@
1
+ import i18n from '@jsb188/app/i18n';
2
+ import { useMutation } from './index';
3
+ import { changePasswordMtn, checkUsernameOrEmailMtn, emailVerificationStatusMtn, requestTokenizedEmailMtn, sendEmailVerificationMtn, signInMtn } from '../gql/mutations/userAuthMutations';
4
+ import type { UseMutationParams } from '@jsb188/graphql/types.d';
5
+ import { useOpenModalPopUp, type OpenModalPopUpFn } from '@jsb188/react/states';
6
+ import { useContext, useState } from 'react';
7
+ import appContext, { onAccountLogin } from '~/shared/states/appContext';
8
+
9
+ /**
10
+ * Types
11
+ */
12
+
13
+ interface SignInParams extends UseMutationParams {
14
+ initialError?: any;
15
+ initialFormData?: Record<string, any>;
16
+ }
17
+
18
+ /**
19
+ * Change password (while logged in)
20
+ */
21
+
22
+ export function useChangePassword(params: UseMutationParams = {}) {
23
+
24
+ const { dispatchApp, appState: { hasPassword, account } } = useContext(appContext);
25
+ const openModalPopUp = useOpenModalPopUp();
26
+ const { onCompleted, onError } = params;
27
+
28
+ const onCompleted_ = (data: any, err: any, variables: any) => {
29
+ if (onCompleted) {
30
+ onCompleted(data, err, variables);
31
+ }
32
+
33
+ const success = !!data?.changePassword;
34
+ if (success) {
35
+ openModalPopUp({
36
+ name: 'password_changed',
37
+ props: {
38
+ title: i18n.t('form.success'),
39
+ message: i18n.t('auth.password_changed_msg'),
40
+ iconName: 'lock-password-filled'
41
+ }
42
+ });
43
+
44
+ if (!hasPassword) {
45
+ dispatchApp({
46
+ __type: 'APP_EDIT_AUTH',
47
+ data: {
48
+ id: account?.id,
49
+ hasPassword: true,
50
+ }
51
+ });
52
+ }
53
+ }
54
+ };
55
+
56
+ const [changePassword, mtnValues] = useMutation(
57
+ changePasswordMtn,
58
+ {
59
+ openModalPopUp,
60
+ onCompleted: onCompleted_,
61
+ onError,
62
+ },
63
+ );
64
+
65
+ return {
66
+ openModalPopUp,
67
+ changePassword,
68
+ ...mtnValues,
69
+ };
70
+ }
71
+
72
+ /**
73
+ * Reset password (from 30m email link)
74
+ */
75
+
76
+ export function useChangePasswordForm(params: UseMutationParams = {}) {
77
+
78
+ const { dispatchApp, appState: { hasPassword, account } } = useContext(appContext);
79
+ const { onCompleted, onError } = params;
80
+
81
+ const onCompleted_ = (data: any, err: any, variables: any) => {
82
+ if (onCompleted) {
83
+ onCompleted(data, err, variables);
84
+ }
85
+
86
+ const success = !!data?.changePassword;
87
+ if (success) {
88
+ // It's possible for user to use this hook without being logged in
89
+ // So we have to check for ID first
90
+ if (account?.id && !hasPassword) {
91
+ dispatchApp({
92
+ __type: 'APP_EDIT_AUTH',
93
+ data: {
94
+ id: account?.id,
95
+ hasPassword: true,
96
+ }
97
+ });
98
+ }
99
+ }
100
+ };
101
+
102
+ const [changePassword, mtnValues] = useMutation(
103
+ changePasswordMtn,
104
+ {
105
+ checkMountedBeforeCallback: true,
106
+ onCompleted: onCompleted_,
107
+ onError,
108
+ },
109
+ );
110
+
111
+ return {
112
+ changePassword,
113
+ ...mtnValues,
114
+ };
115
+ }
116
+
117
+ /**
118
+ * Check email verification status
119
+ */
120
+
121
+ export function useEmailVerification(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
122
+
123
+ const { onCompleted, onError } = params;
124
+ const [emailVerificationStatus, mtnValues1] = useMutation(
125
+ emailVerificationStatusMtn,
126
+ {
127
+ openModalPopUp,
128
+ onError,
129
+ onCompleted,
130
+ },
131
+ );
132
+
133
+ const [sendEmailVerification, mtnValues2] = useMutation(
134
+ sendEmailVerificationMtn,
135
+ {
136
+ openModalPopUp,
137
+ onError,
138
+ onCompleted,
139
+ },
140
+ );
141
+
142
+ return {
143
+ emailVerificationStatus,
144
+ sendEmailVerification,
145
+ verifying: mtnValues1.saving,
146
+ sending: mtnValues2.saving,
147
+ };
148
+ }
149
+
150
+ /**
151
+ * Request password reset (email with link)
152
+ */
153
+
154
+ export function useRequestTokenizedEmail(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
155
+
156
+ const { onCompleted, onError } = params;
157
+ const [requestTokenizedEmail, mtnValues] = useMutation(
158
+ requestTokenizedEmailMtn,
159
+ {
160
+ checkMountedBeforeCallback: true,
161
+ openModalPopUp,
162
+ onCompleted,
163
+ onError
164
+ },
165
+ );
166
+
167
+ return {
168
+ requestTokenizedEmail,
169
+ ...mtnValues,
170
+ };
171
+ }
172
+
173
+ /**
174
+ * Sign in
175
+ */
176
+
177
+ export function useSignIn(params: SignInParams = {}, openModalPopUp?: OpenModalPopUpFn) {
178
+ const { onError, onCompleted, initialError, initialFormData } = params;
179
+ const { dispatchApp } = useContext<any>(appContext);
180
+
181
+ const [dataForSchema, setDataForSchema] = useState({
182
+ hasInput: !!initialFormData?.usernameOrEmail,
183
+ lastIdentifier: initialFormData?.usernameOrEmail || '',
184
+ hidePassword: !initialFormData?.usernameOrEmail,
185
+ });
186
+
187
+ const [checkUsernameOrEmail, step1MtnValues, step1MtnHandlers] = useMutation(
188
+ checkUsernameOrEmailMtn,
189
+ {
190
+ openModalPopUp,
191
+ initialError,
192
+ onError,
193
+ onCompleted,
194
+ },
195
+ );
196
+
197
+ const [signIn, step2MtnValues, step2MtnHandlers] = useMutation(
198
+ signInMtn,
199
+ {
200
+ openModalPopUp,
201
+ initialError,
202
+ onError,
203
+ onCompleted: (data, error) => {
204
+ const result = data?.signIn;
205
+ if (result?.token && result.user?.id) {
206
+ onAccountLogin(result, dispatchApp);
207
+
208
+ if (onCompleted) {
209
+ onCompleted(data, error);
210
+ }
211
+ }
212
+ },
213
+ },
214
+ );
215
+
216
+ let mtnValues;
217
+ let mtnHandlers;
218
+ if (dataForSchema.hidePassword) {
219
+ mtnValues = step1MtnValues;
220
+ mtnHandlers = step1MtnHandlers;
221
+ } else {
222
+ mtnValues = step2MtnValues;
223
+ mtnHandlers = step2MtnHandlers;
224
+ }
225
+
226
+ return {
227
+ ...mtnValues,
228
+ ...mtnHandlers,
229
+ checkUsernameOrEmail,
230
+ signIn,
231
+ dataForSchema,
232
+ setDataForSchema,
233
+ };
234
+ }
@@ -0,0 +1,49 @@
1
+ import type { PaginationArgs, UseQueryParams } from '../types.d';
2
+ import { useQuery } from '../client';
3
+ import { journalEntriesQry } from '../gql/queries/journalQueries';
4
+
5
+ /**
6
+ * Constants
7
+ */
8
+
9
+ const JOURNAL_ENTRIES_LIMIT = 50;
10
+
11
+ /**
12
+ * Types
13
+ */
14
+
15
+ interface JournalEntriesVariables {
16
+ organizationId?: string;
17
+ accountId?: string;
18
+ }
19
+
20
+ interface JournalEntriesArgs extends PaginationArgs {
21
+ organizationId: string;
22
+ accountId?: string;
23
+ timeZone: string | null;
24
+ filter: FilterJournalEntriesArgs;
25
+ }
26
+
27
+ /**
28
+ * Fetch journal entries
29
+ */
30
+
31
+ export function useJournalEntries(variables: JournalEntriesArgs, params: UseQueryParams = {}) {
32
+
33
+ const { data, ...other } = useQuery(journalEntriesQry, {
34
+ variables: {
35
+ ...variables,
36
+ cursor: null,
37
+ after: true,
38
+ limit: JOURNAL_ENTRIES_LIMIT
39
+ },
40
+ // If this query is used for virtualized list pagination, set {params.skip=true}
41
+ skip: !variables.organizationId,
42
+ ...params,
43
+ });
44
+
45
+ return {
46
+ journalEntries: data?.journalEntries,
47
+ ...other
48
+ };
49
+ }
@@ -0,0 +1,37 @@
1
+ import { useQuery } from '@jsb188/graphql/client';
2
+ import { organizationRelationshipQry, myOrganizationsQry } from '../gql/queries/organizationQueries';
3
+ import type { UseQueryParams } from '../types.d';
4
+
5
+ /**
6
+ * Fetch organization relationship
7
+ */
8
+
9
+ export function useOrganizationRelationship(organizationId?: string | null, params: UseQueryParams = {}) {
10
+ const { data, ...other } = useQuery(organizationRelationshipQry, {
11
+ variables: {
12
+ organizationId
13
+ },
14
+ skip: !organizationId,
15
+ ...params,
16
+ });
17
+
18
+ return {
19
+ organizationRelationship: data?.organizationRelationship,
20
+ ...other
21
+ };
22
+ }
23
+
24
+ /**
25
+ * Fetch my organizations
26
+ */
27
+
28
+ export function useMyOrganizations(params: UseQueryParams = {}) {
29
+ const { data, ...other } = useQuery(myOrganizationsQry, {
30
+ ...params,
31
+ });
32
+
33
+ return {
34
+ myOrganizations: data?.myOrganizations,
35
+ ...other
36
+ };
37
+ }
package/package.json CHANGED
@@ -1,36 +1,50 @@
1
1
  {
2
2
  "name": "@jsb188/graphql",
3
- "version": "1.0.4",
3
+ "version": "1.1.1",
4
4
  "description": "GraphQL client for react, using recoil",
5
5
  "license": "ISC",
6
6
  "author": "jsb188",
7
7
  "type": "module",
8
8
  "types": "types.d.ts",
9
9
  "exports": {
10
- "./fragments/auth": "./gql/fragments/authFragments.ts",
10
+ "./fragments/account": "./gql/fragments/accountFragments.ts",
11
+ "./fragments/accountAuth": "./gql/fragments/accountAuthFragments.ts",
11
12
  "./fragments/aiChat": "./gql/fragments/aiChatFragments.ts",
12
13
  "./fragments/billing": "./gql/fragments/billingFragments.ts",
13
14
  "./fragments/card": "./gql/fragments/cardFragments.ts",
14
15
  "./fragments/chat": "./gql/fragments/chatFragments.ts",
16
+ "./fragments/journal": "./gql/fragments/journalFragments.ts",
17
+ "./fragments/organization": "./gql/fragments/organizationFragments.ts",
15
18
  "./fragments/other": "./gql/fragments/otherFragments.ts",
16
19
  "./fragments/user": "./gql/fragments/userFragments.ts",
20
+ "./fragments/userAuth": "./gql/fragments/userAuthFragments.ts",
21
+ "./hooks": "./hooks/",
22
+ "./hooks/use-aiChat-qry": "./hooks/use-aiChat-qry.ts",
23
+ "./hooks/use-app-qry": "./hooks/use-app-qry.ts",
24
+ "./hooks/use-journal-qry": "./hooks/use-journal-qry.ts",
25
+ "./hooks/use-organization-qry": "./hooks/use-organization-qry.ts",
26
+ "./hooks/use-auth-mtn": "./hooks/use-auth-mtn.ts",
27
+ "./mutations/accountAuth": "./gql/mutations/accountAuthMutations.ts",
17
28
  "./mutations/aiChat": "./gql/mutations/aiChatMutations.ts",
18
- "./mutations/auth": "./gql/mutations/authMutations.ts",
19
29
  "./mutations/billing": "./gql/mutations/billingMutations.ts",
20
30
  "./mutations/chat": "./gql/mutations/chatMutations.ts",
31
+ "./mutations/journal": "./gql/mutations/journalMutations.ts",
21
32
  "./mutations/other": "./gql/mutations/otherMutations.ts",
22
33
  "./mutations/user": "./gql/mutations/userMutations.ts",
34
+ "./mutations/userAuth": "./gql/mutations/userAuthMutations.ts",
23
35
  "./queries/aiChat": "./gql/queries/aiChatQueries.ts",
24
- "./queries/auth": "./gql/queries/authQueries.ts",
36
+ "./queries/app": "./gql/queries/appQueries.ts",
25
37
  "./queries/billing": "./gql/queries/billingQueries.ts",
26
38
  "./queries/card": "./gql/queries/cardQueries.ts",
27
39
  "./queries/chat": "./gql/queries/chatQueries.ts",
40
+ "./queries/journal": "./gql/queries/journalQueries.ts",
41
+ "./queries/organization": "./gql/queries/organizationQueries.ts",
28
42
  "./queries/other": "./gql/queries/otherQueries.ts",
29
43
  "./queries/user": "./gql/queries/userQueries.ts",
30
44
  "./cache": "./cache/index.ts",
31
45
  "./client": "./client/index.ts",
32
46
  "./sse": "./sse.ts",
33
- "./types": "./types.d.ts",
47
+ "./types.d": "./types.d.ts",
34
48
  "./utils": "./utils.ts"
35
49
  },
36
50
  "scripts": {
@@ -41,7 +55,7 @@
41
55
  "graphql-tag": "^2.12.6"
42
56
  },
43
57
  "peerDependencies": {
44
- "@jsb188/app": "^1.0.4",
45
- "@jsb188/react": "^1.0.4"
58
+ "@jsb188/app": "1.1.1",
59
+ "@jsb188/react": "1.1.1"
46
60
  }
47
61
  }
package/sse.ts CHANGED
@@ -1,5 +1,5 @@
1
+ import { addFragmentToCache, updateFragment, updateQuery } from './cache/';
1
2
  import type { UpdateObserversFn } from './types.d';
2
- import { loadFragment, updateQuery, updateFragment, addFragmentToCache } from './cache/';
3
3
 
4
4
  /**
5
5
  * Types
@@ -14,12 +14,13 @@ type ValidSSEType = (
14
14
  'DATA_APPEND' | 'DATA_PREPEND' | 'DATA_UPDATE'
15
15
  );
16
16
 
17
- interface PublishPayload {
17
+ export interface PublishPayload {
18
18
  __type: ValidSSEType;
19
19
  fragmentKey: string;
20
20
  fragmentNamespace?: string;
21
21
  dataFragmentKey?: string;
22
22
  data: Record<string, any>;
23
+ otherData?: Record<string, any>;
23
24
  }
24
25
 
25
26
  /**
@@ -28,10 +29,10 @@ interface PublishPayload {
28
29
 
29
30
  function handleQueryConcat(payload: PublishPayload, updateObservers?: UpdateObserversFn) {
30
31
 
31
- const { __type, fragmentKey, fragmentNamespace, dataFragmentKey, data } = payload;
32
+ const { __type, fragmentKey, fragmentNamespace, dataFragmentKey, data, otherData } = payload;
33
+
32
34
  if (fragmentKey && fragmentNamespace && dataFragmentKey && data) {
33
35
  const isAppend = __type === 'QUERY_APPEND';
34
-
35
36
  const updateData = (currentData: any) => {
36
37
  const currentList = currentData?.[fragmentNamespace]?.data;
37
38
  if (
@@ -41,9 +42,9 @@ function handleQueryConcat(payload: PublishPayload, updateObservers?: UpdateObse
41
42
  ) {
42
43
  addFragmentToCache(dataFragmentKey, data);
43
44
  const updatedList = isAppend ? [...currentList, [dataFragmentKey]] : [[dataFragmentKey], ...currentList];
44
-
45
45
  return {
46
46
  ...currentData,
47
+ ...otherData,
47
48
  [fragmentNamespace]: {
48
49
  ...currentData?.[fragmentNamespace],
49
50
  data: updatedList
@@ -60,6 +61,8 @@ function handleQueryConcat(payload: PublishPayload, updateObservers?: UpdateObse
60
61
  updateObservers
61
62
  );
62
63
  }
64
+
65
+ return null;
63
66
  }
64
67
 
65
68
  /**
@@ -67,30 +70,29 @@ function handleQueryConcat(payload: PublishPayload, updateObservers?: UpdateObse
67
70
  */
68
71
 
69
72
  function handleFragmentConcat(payload: PublishPayload, updateObservers?: UpdateObserversFn) {
70
- const { __type, fragmentKey, fragmentNamespace, data } = payload;
73
+ const { __type, fragmentKey, fragmentNamespace, data, otherData } = payload;
71
74
  const isAppend = __type === 'DATA_APPEND';
72
75
 
73
76
  if (fragmentKey && fragmentNamespace && data) {
74
77
  const namespaceType = typeof fragmentNamespace;
75
78
  const updateData = (currentData: any) => {
76
79
  if (typeof currentData[fragmentNamespace] === namespaceType) {
77
-
78
80
  let nextValue;
79
81
  if (namespaceType === 'string') {
80
82
  nextValue = isAppend ? `${currentData[fragmentNamespace]}${data}` : `${data}${currentData[fragmentNamespace]}`;
81
83
  } else if (Array.isArray(currentData[fragmentNamespace])) {
82
84
  nextValue = isAppend ? [...currentData[fragmentNamespace], data] : [data, ...currentData[fragmentNamespace]];
83
85
  }
84
-
85
86
  return {
86
87
  ...currentData,
88
+ ...otherData,
87
89
  [fragmentNamespace]: nextValue
88
90
  }
89
91
  }
90
92
  return currentData;
91
93
  };
92
94
 
93
- updateFragment(fragmentKey, updateData, null, isAppend, updateObservers);
95
+ updateFragment(fragmentKey, updateData, null, false, updateObservers);
94
96
  }
95
97
 
96
98
  }
@@ -102,11 +104,6 @@ function handleFragmentConcat(payload: PublishPayload, updateObservers?: UpdateO
102
104
  function handleFragmentUpdate(payload: PublishPayload, updateObservers?: UpdateObserversFn) {
103
105
  const { fragmentKey, dataFragmentKey, data } = payload;
104
106
  updateFragment(dataFragmentKey || fragmentKey, data, null, false, updateObservers);
105
-
106
- console.log(
107
- loadFragment(fragmentKey),
108
- );
109
-
110
107
  }
111
108
 
112
109
  /**
@@ -114,22 +111,18 @@ function handleFragmentUpdate(payload: PublishPayload, updateObservers?: UpdateO
114
111
  */
115
112
 
116
113
  function handleSSEData(payload: PublishPayload, updateObservers?: UpdateObserversFn) {
117
-
118
114
  switch (payload.__type) {
119
115
  case 'CONNECTED':
120
116
  // Do nothing
121
117
  break;
122
118
  case 'QUERY_APPEND':
123
119
  case 'QUERY_PREPEND':
124
- handleQueryConcat(payload, updateObservers)
125
- break;
120
+ return handleQueryConcat(payload, updateObservers)
126
121
  case 'DATA_APPEND':
127
122
  case 'DATA_PREPEND':
128
- handleFragmentConcat(payload, updateObservers)
129
- break;
123
+ return handleFragmentConcat(payload, updateObservers)
130
124
  case 'DATA_UPDATE':
131
- handleFragmentUpdate(payload, updateObservers)
132
- break;
125
+ return handleFragmentUpdate(payload, updateObservers)
133
126
  default:
134
127
  console.log('Unknown {__type} in handleSSEData():', payload.__type);
135
128
  break;
package/types.d.ts CHANGED
@@ -1,4 +1,8 @@
1
- import type { ServerErrorObj, SimpleErrorType } from '@jsb188/app/types/app';
1
+ import type { ServerErrorObj, SimpleErrorType } from '@jsb188/app/types/app.d';
2
+
3
+ /**
4
+ * GraphQL API requests
5
+ */
2
6
 
3
7
  export interface APIRequestOutput {
4
8
  aborted?: boolean;
@@ -18,12 +22,18 @@ export interface UpdateDataObserverArgs {
18
22
  forceRefetch?: boolean;
19
23
  }
20
24
 
25
+ /**
26
+ * GraphQL client handlers
27
+ */
28
+
21
29
  export type AnyModalPopUpFn = (data: any, err?: ServerErrorObj) => void;
22
30
  export type UpdateObserversFn = (args: UpdateDataObserverArgs) => void;
23
- export type OnCompletedGQLFn = (data: any, error: ServerErrorObj | null, variables: any) => void;
31
+ export type OnCompletedGQLFn = (data: any, error: ServerErrorObj | null, variables?: any) => void;
24
32
  export type OnErrorGQLFn = (error: ServerErrorObj | null, variables: any) => void;
25
33
 
26
- // GraphQL query hook options
34
+ /**
35
+ * GraphQL query hook params
36
+ */
27
37
 
28
38
  export interface GraphQLQueryOptions {
29
39
  name?: string;
@@ -39,19 +49,26 @@ export interface GraphQLQueryOptions {
39
49
  }
40
50
 
41
51
  // Params for most GraphQL (query) hooks
42
-
43
52
  export type UseQueryParams = Omit<GraphQLQueryOptions, 'name' | 'retryCount' | 'cacheMap'>;
44
53
 
45
54
  // Params for most GraphQL (mutation) hooks
46
-
47
55
  export type UseMutationParams = Partial<{
48
56
  onCompleted: OnCompletedGQLFn;
49
57
  onError: OnErrorGQLFn;
50
58
  }>;
51
59
 
52
-
53
60
  // Params for most GraphQL hooks with these options
54
-
55
61
  export type UseMutationParamsExtra = Partial<{
56
62
  checkMountedBeforeCallback?: boolean;
57
63
  }> & UseMutationParams;
64
+
65
+ /**
66
+ * Common query patterns
67
+ */
68
+
69
+ export type PaginationArgs = Partial<{
70
+ cursor: [number | null, number | null];
71
+ after: boolean;
72
+ limit: number;
73
+ doNotThrowError: boolean;
74
+ }>;
package/utils.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { getENVVariable } from '@jsb188/app';
2
- import type { ServerErrorObj } from '@jsb188/app/types/app';
2
+ import type { ServerErrorObj } from '@jsb188/app/types/app.d';
3
3
 
4
4
  const TIME_TRACKER = new Map();
5
5
 
@@ -60,25 +60,28 @@ export function isServerErrorGQL(apiResult: any): boolean {
60
60
  * Headers for all network requests
61
61
  */
62
62
 
63
- export function apiRequestHeaders(authorization: string | null | undefined): any {
64
- const headers = {
63
+ export function apiRequestHeaders(authorization?: string | null, ipAddress?: string | null): Headers {
64
+ const headers: Record<string, string> = {
65
65
  'Content-Type': 'application/json; charset=utf-8',
66
- api_key: getENVVariable('GQL_API_KEY'),
67
- origin: getENVVariable('APP_URL'),
68
- 'Access-Control-Allow-Origin': getENVVariable('APP_URL'),
66
+ api_key: String(getENVVariable('GQL_API_KEY') || ''),
67
+ origin: String(getENVVariable('APP_URL') || ''),
68
+ 'Access-Control-Allow-Origin': String(getENVVariable('APP_URL') || ''),
69
69
  // recaptcha: ? // Not sure if we're going to do this later any more
70
70
  };
71
71
 
72
72
  if (!getENVVariable('IS_BROWSER')) {
73
- // @ts-expect-error Can't allow undefined or null
74
73
  headers.ssr = '1';
74
+
75
+ if (ipAddress) {
76
+ // Do not allow undefined or null, it becomes a String type
77
+ headers['x-ssr-ip'] = ipAddress;
78
+ }
75
79
  }
76
80
 
77
81
  if (authorization) {
78
- // Do not send undefined or null, it will become a String type
79
- // @ts-expect-error Can't allow undefined or null
82
+ // Do not send undefined or null, it becomes a String type
80
83
  headers.authorization = authorization;
81
84
  }
82
85
 
83
- return headers;
86
+ return new Headers(headers);
84
87
  }
File without changes