@jsb188/graphql 1.0.4 → 1.1.3

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.
@@ -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,322 @@
1
+ import i18n from '@jsb188/app/i18n';
2
+ import { useMutation } from './index';
3
+ import type { UseMutationParams } from '@jsb188/graphql/types.d';
4
+ import { deleteAuthToken } from '@jsb188/app/platform';
5
+ import { changePasswordMtn, checkUsernameOrEmailMtn, emailVerificationStatusMtn, requestTokenizedEmailMtn, sendEmailVerificationMtn, signInMtn, signUpMtn, signOutMtn } from '../gql/mutations/userAuthMutations';
6
+ import type { OpenModalPopUpFn } from '@jsb188/react/states';
7
+ import { AppContext, onAccountLogin, onGuestInit, useOpenModalPopUp } from '@jsb188/react/states';
8
+ import React, { useEffect, useContext, useState } from 'react';
9
+
10
+ /**
11
+ * Types
12
+ */
13
+
14
+ interface SignInParams extends UseMutationParams {
15
+ initialError?: any;
16
+ initialFormData?: Record<string, any>;
17
+ }
18
+
19
+ /**
20
+ * Change password (while logged in)
21
+ */
22
+
23
+ export function useChangePassword(params: UseMutationParams = {}) {
24
+
25
+ const { dispatchApp, appState: { hasPassword, account } } = useContext(AppContext);
26
+ const openModalPopUp = useOpenModalPopUp();
27
+ const { onCompleted, onError } = params;
28
+
29
+ const onCompleted_ = (data: any, err: any, variables: any) => {
30
+ if (onCompleted) {
31
+ onCompleted(data, err, variables);
32
+ }
33
+
34
+ const success = !!data?.changePassword;
35
+ if (success) {
36
+ openModalPopUp({
37
+ name: 'password_changed',
38
+ props: {
39
+ title: i18n.t('form.success'),
40
+ message: i18n.t('auth.password_changed_msg'),
41
+ iconName: 'lock-password-filled'
42
+ }
43
+ });
44
+
45
+ if (!hasPassword) {
46
+ dispatchApp({
47
+ __type: 'APP_EDIT_AUTH',
48
+ data: {
49
+ id: account?.id,
50
+ hasPassword: true,
51
+ }
52
+ });
53
+ }
54
+ }
55
+ };
56
+
57
+ const [changePassword, mtnValues] = useMutation(
58
+ changePasswordMtn,
59
+ {
60
+ openModalPopUp,
61
+ onCompleted: onCompleted_,
62
+ onError,
63
+ },
64
+ );
65
+
66
+ return {
67
+ openModalPopUp,
68
+ changePassword,
69
+ ...mtnValues,
70
+ };
71
+ }
72
+
73
+ /**
74
+ * Reset password (from 30m email link)
75
+ */
76
+
77
+ export function useChangePasswordForm(params: UseMutationParams = {}) {
78
+
79
+ const { dispatchApp, appState: { hasPassword, account } } = useContext(AppContext);
80
+ const { onCompleted, onError } = params;
81
+
82
+ const onCompleted_ = (data: any, err: any, variables: any) => {
83
+ if (onCompleted) {
84
+ onCompleted(data, err, variables);
85
+ }
86
+
87
+ const success = !!data?.changePassword;
88
+ if (success) {
89
+ // It's possible for user to use this hook without being logged in
90
+ // So we have to check for ID first
91
+ if (account?.id && !hasPassword) {
92
+ dispatchApp({
93
+ __type: 'APP_EDIT_AUTH',
94
+ data: {
95
+ id: account?.id,
96
+ hasPassword: true,
97
+ }
98
+ });
99
+ }
100
+ }
101
+ };
102
+
103
+ const [changePassword, mtnValues] = useMutation(
104
+ changePasswordMtn,
105
+ {
106
+ checkMountedBeforeCallback: true,
107
+ onCompleted: onCompleted_,
108
+ onError,
109
+ },
110
+ );
111
+
112
+ return {
113
+ changePassword,
114
+ ...mtnValues,
115
+ };
116
+ }
117
+
118
+ /**
119
+ * Check email verification status
120
+ */
121
+
122
+ export function useEmailVerification(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
123
+
124
+ const { onCompleted, onError } = params;
125
+ const [emailVerificationStatus, mtnValues1] = useMutation(
126
+ emailVerificationStatusMtn,
127
+ {
128
+ openModalPopUp,
129
+ onError,
130
+ onCompleted,
131
+ },
132
+ );
133
+
134
+ const [sendEmailVerification, mtnValues2] = useMutation(
135
+ sendEmailVerificationMtn,
136
+ {
137
+ openModalPopUp,
138
+ onError,
139
+ onCompleted,
140
+ },
141
+ );
142
+
143
+ return {
144
+ emailVerificationStatus,
145
+ sendEmailVerification,
146
+ verifying: mtnValues1.saving,
147
+ sending: mtnValues2.saving,
148
+ };
149
+ }
150
+
151
+ /**
152
+ * Request password reset (email with link)
153
+ */
154
+
155
+ export function useRequestTokenizedEmail(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
156
+
157
+ const { onCompleted, onError } = params;
158
+ const [requestTokenizedEmail, mtnValues] = useMutation(
159
+ requestTokenizedEmailMtn,
160
+ {
161
+ checkMountedBeforeCallback: true,
162
+ openModalPopUp,
163
+ onCompleted,
164
+ onError
165
+ },
166
+ );
167
+
168
+ return {
169
+ requestTokenizedEmail,
170
+ ...mtnValues,
171
+ };
172
+ }
173
+
174
+ /**
175
+ * Sign in
176
+ */
177
+
178
+ export function useSignIn(params: SignInParams = {}, openModalPopUp?: OpenModalPopUpFn) {
179
+ const { onError, onCompleted, initialError, initialFormData } = params;
180
+ const { dispatchApp } = useContext<any>(AppContext);
181
+
182
+ const [dataForSchema, setDataForSchema] = useState({
183
+ hasInput: !!initialFormData?.usernameOrEmail,
184
+ lastIdentifier: initialFormData?.usernameOrEmail || '',
185
+ hidePassword: !initialFormData?.usernameOrEmail,
186
+ });
187
+
188
+ const [checkUsernameOrEmail, step1MtnValues, step1MtnHandlers] = useMutation(
189
+ checkUsernameOrEmailMtn,
190
+ {
191
+ openModalPopUp,
192
+ initialError,
193
+ onError,
194
+ onCompleted,
195
+ },
196
+ );
197
+
198
+ const [signIn, step2MtnValues, step2MtnHandlers] = useMutation(
199
+ signInMtn,
200
+ {
201
+ openModalPopUp,
202
+ initialError,
203
+ onError,
204
+ onCompleted: (data, error) => {
205
+ const result = data?.signIn;
206
+ if (result?.token && result.user?.id) {
207
+ onAccountLogin(result, dispatchApp);
208
+
209
+ if (onCompleted) {
210
+ onCompleted(data, error);
211
+ }
212
+ }
213
+ },
214
+ },
215
+ );
216
+
217
+ let mtnValues;
218
+ let mtnHandlers;
219
+ if (dataForSchema.hidePassword) {
220
+ mtnValues = step1MtnValues;
221
+ mtnHandlers = step1MtnHandlers;
222
+ } else {
223
+ mtnValues = step2MtnValues;
224
+ mtnHandlers = step2MtnHandlers;
225
+ }
226
+
227
+ return {
228
+ ...mtnValues,
229
+ ...mtnHandlers,
230
+ checkUsernameOrEmail,
231
+ signIn,
232
+ dataForSchema,
233
+ setDataForSchema,
234
+ };
235
+ }
236
+
237
+ // Before are deprecated HOC that needs to be migrated to hooks
238
+ // Before are deprecated HOC that needs to be migrated to hooks
239
+ // Before are deprecated HOC that needs to be migrated to hooks
240
+ // Before are deprecated HOC that needs to be migrated to hooks
241
+ // Before are deprecated HOC that needs to be migrated to hooks
242
+
243
+ /**
244
+ * Sign up
245
+ */
246
+
247
+ export function composeSignUp(Cmp: React.FC<any>) {
248
+ const SignUpCnt = (p) => {
249
+ const { doNotAlertErrors, onError, onCompleted } = p;
250
+ const openModalPopUp = useOpenModalPopUp();
251
+
252
+ const [signUp, mtnValues, mtnHandlers] = useMutation(
253
+ signUpMtn,
254
+ {
255
+ openModalPopUp: doNotAlertErrors ? null : openModalPopUp,
256
+ onError,
257
+ onCompleted,
258
+ },
259
+ );
260
+
261
+ // return (
262
+ // <Cmp
263
+ // {...p}
264
+ // {...mtnValues}
265
+ // {...mtnHandlers}
266
+ // signUp={signUp}
267
+ // />
268
+ // );
269
+
270
+ return 'This page is not done yet.'
271
+ };
272
+
273
+ return SignUpCnt;
274
+ }
275
+
276
+ /**
277
+ * Sign out
278
+ */
279
+
280
+ export function composeSignOut(Cmp: React.FC<any>) {
281
+ const SignOutCnt = (p) => {
282
+ const { doNotAlertErrors, onError, onCompleted } = p;
283
+ const openModalPopUp = useOpenModalPopUp();
284
+ const { dispatchApp } = useContext<any>(AppContext);
285
+
286
+ const [signOut, mtnValues, mtnHandlers] = useMutation(
287
+ signOutMtn,
288
+ {
289
+ openModalPopUp: doNotAlertErrors ? null : openModalPopUp,
290
+ onError,
291
+ onCompleted: (data) => {
292
+ if (data?.signOut) {
293
+ deleteAuthToken();
294
+ onGuestInit(null, dispatchApp);
295
+ }
296
+ if (onCompleted) {
297
+ onCompleted(data);
298
+ }
299
+ },
300
+ },
301
+ );
302
+
303
+ useEffect(() => {
304
+ const timer = setTimeout(() => {
305
+ signOut();
306
+ }, 1000);
307
+ return () => clearTimeout(timer);
308
+ }, []);
309
+
310
+ // return (
311
+ // <Cmp
312
+ // {...p}
313
+ // {...mtnValues}
314
+ // {...mtnHandlers}
315
+ // signOut={signOut}
316
+ // />
317
+ // );
318
+ return null;
319
+ };
320
+
321
+ return SignOutCnt;
322
+ }
@@ -0,0 +1,50 @@
1
+ import type { PaginationArgs, UseQueryParams } from '../types.d';
2
+ import { useQuery } from '../client';
3
+ import { journalEntriesQry } from '../gql/queries/journalQueries';
4
+ import type { FilterJournalEntriesArgs } from '@jsb188/app/types/journal.d';
5
+
6
+ /**
7
+ * Constants
8
+ */
9
+
10
+ const JOURNAL_ENTRIES_LIMIT = 50;
11
+
12
+ /**
13
+ * Types
14
+ */
15
+
16
+ interface JournalEntriesVariables {
17
+ organizationId?: string;
18
+ accountId?: string;
19
+ }
20
+
21
+ interface JournalEntriesArgs extends PaginationArgs {
22
+ organizationId: string;
23
+ accountId?: string;
24
+ timeZone: string | null;
25
+ filter: FilterJournalEntriesArgs;
26
+ }
27
+
28
+ /**
29
+ * Fetch journal entries
30
+ */
31
+
32
+ export function useJournalEntries(variables: JournalEntriesArgs, params: UseQueryParams = {}) {
33
+
34
+ const { data, ...other } = useQuery(journalEntriesQry, {
35
+ variables: {
36
+ ...variables,
37
+ cursor: null,
38
+ after: true,
39
+ limit: JOURNAL_ENTRIES_LIMIT
40
+ },
41
+ // If this query is used for virtualized list pagination, set {params.skip=true}
42
+ skip: !variables.organizationId,
43
+ ...params,
44
+ });
45
+
46
+ return {
47
+ journalEntries: data?.journalEntries,
48
+ ...other
49
+ };
50
+ }
@@ -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.3",
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.3",
59
+ "@jsb188/react": "1.1.3"
46
60
  }
47
61
  }