@jsb188/graphql 1.0.1 → 1.0.4

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,2 @@
1
+ export * from './hooks';
2
+ export * from './request';
@@ -0,0 +1,194 @@
1
+ import { getENVVariable } from '@jsb188/app';
2
+ import type { ServerErrorObj } from '@jsb188/app/types/app';
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
+ retryCount: number;
16
+ variables: any;
17
+ cacheMap: any;
18
+ openModalPopUp: any;
19
+ initialError: any;
20
+ onCompleted: OnCompletedGQLFn;
21
+ onError: OnErrorGQLFn;
22
+ }>;
23
+
24
+ /**
25
+ * Helper: Get name of query
26
+ */
27
+
28
+ // function getQueryName(query: any) {
29
+ // return query.definitions.filter((d: any) => d.kind === 'OperationDefinition').map(d => d.name.value).join(', ');
30
+ // }
31
+
32
+ /**
33
+ * Helper; Log if conditions are met
34
+ */
35
+
36
+ // function doLog(query: any, logStr: string) {
37
+ // const queryName = getQueryName(query);
38
+ // if (queryName === 'friend') {
39
+ // console.log(logStr.replace(/\$0/gi, queryName));
40
+ // }
41
+ // }
42
+
43
+ /**
44
+ * Default params for graphql requests
45
+ */
46
+
47
+ const defaultRequestParams = {
48
+ // onCompleted: (data: any) => {
49
+ // if (getENVVariable('NODE_ENV') === 'development') {
50
+ // console.log('onCompleted:', data);
51
+ // }
52
+ // },
53
+ onError: (error: ServerErrorObj | null) => {
54
+ if (getENVVariable('NODE_ENV') === 'development') {
55
+ console.log('DEVELOPMENT onError():', error);
56
+ }
57
+ },
58
+ };
59
+
60
+ /**
61
+ * GraphQL request with retry support
62
+ */
63
+
64
+ export async function graphqlRequestWithRetry(
65
+ gqlQuery: any,
66
+ graphqlOptions: GraphQLMutationOptions = defaultRequestParams,
67
+ triedCount: number = 0,
68
+ ): Promise<any> {
69
+
70
+ const retryCount = graphqlOptions?.retryCount || 0;
71
+ const retryDelay = 1500 * Math.pow(2, triedCount);
72
+ const { onCompleted, onError, openModalPopUp } = graphqlOptions;
73
+
74
+ const apiResult = await graphqlRequest(
75
+ gqlQuery,
76
+ graphqlOptions?.variables,
77
+ {
78
+ openModalPopUp: retryCount >= triedCount ? openModalPopUp : undefined,
79
+ onCompleted: (data: any | null, error: ServerErrorObj | null) => {
80
+ if (onCompleted && data.data) {
81
+ onCompleted(data.data, error, graphqlOptions?.variables);
82
+ }
83
+ },
84
+ onError: (error: ServerErrorObj | null) => {
85
+ if (onError && retryCount <= triedCount) {
86
+ onError(error, graphqlOptions?.variables);
87
+ } else if (!onError) {
88
+ console.warn(error);
89
+ }
90
+ },
91
+ }
92
+ );
93
+
94
+ if (!apiResult.data && isServerErrorGQL(apiResult)) {
95
+ if (retryCount > triedCount) {
96
+ await delay(retryDelay);
97
+ if (getENVVariable('NODE_ENV') === 'development') {
98
+ console.log(`retrying mutation... ${triedCount + 1} / ${retryCount}`);
99
+ }
100
+
101
+ return graphqlRequestWithRetry(gqlQuery, graphqlOptions, triedCount + 1);
102
+ } else if (getENVVariable('NODE_ENV') === 'development') {
103
+ console.log(
104
+ `mutation failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`,
105
+ );
106
+ }
107
+ }
108
+
109
+ return apiResult.data || apiResult;
110
+ }
111
+
112
+ /**
113
+ * GraphQL query
114
+ */
115
+
116
+ export async function graphqlRequest(
117
+ gqlQuery: any,
118
+ variables?: any,
119
+ params?: GraphQLMutationOptions,
120
+ controllerSignal?: AbortSignal | null,
121
+ updateObservers?: UpdateObserversFn,
122
+ ): Promise<any> {
123
+
124
+ const { openModalPopUp, onCompleted, onError, authToken, cacheMap } = params || {};
125
+
126
+ if (!gqlQuery?.definitions) {
127
+ console.log(gqlQuery);
128
+ }
129
+
130
+ const operationName = gqlQuery?.definitions?.find((def: any) => def.kind === 'OperationDefinition')?.name?.value;
131
+ const headers = apiRequestHeaders(getENVVariable('IS_BROWSER') ? getAuthToken() : authToken);
132
+
133
+ // Use this to check queries that are getting double-requested
134
+ // doLog(gqlQuery, 'QUERYING... $0');
135
+
136
+ return fetch(getENVVariable('GQL_SERVER')!, {
137
+ signal: controllerSignal,
138
+ method: 'POST',
139
+ // credentials: 'same-origin',
140
+ // headers: new Headers({
141
+ headers: new Headers(headers),
142
+ // headers,
143
+ body: JSON.stringify({
144
+ query: gqlQuery?.loc?.source.body,
145
+ variables,
146
+ operationName,
147
+ }),
148
+ })
149
+ .then((response) => response.json())
150
+ .then((data) => {
151
+ let gqlError: ServerErrorObj | null = null;
152
+ if (data.errors?.length) {
153
+ gqlError = normalizeServerError(data);
154
+
155
+ if (openModalPopUp) {
156
+ openModalPopUp(null, gqlError);
157
+ }
158
+
159
+ if (onError) {
160
+ onError(gqlError, variables);
161
+ }
162
+ }
163
+
164
+ if (onCompleted) {
165
+ onCompleted(data, gqlError, variables);
166
+ }
167
+
168
+ setDataToCache(data.data, gqlQuery, variables, cacheMap, updateObservers);
169
+
170
+ return {
171
+ ...data.data,
172
+ error: gqlError,
173
+ };
174
+ })
175
+ .catch((err) => {
176
+ if (getENVVariable('NODE_ENV') === 'development') {
177
+ console.log(err);
178
+ }
179
+
180
+ if (err.name === 'AbortError') {
181
+ return { aborted: true };
182
+ }
183
+
184
+ const gqlError = normalizeServerError(err);
185
+ if (openModalPopUp) {
186
+ openModalPopUp(null, gqlError);
187
+ }
188
+
189
+ if (onError) {
190
+ onError(gqlError, variables);
191
+ }
192
+ return { error: gqlError };
193
+ });
194
+ }
@@ -0,0 +1,16 @@
1
+ export const aiChatFragment = `fragment aiChatFragment on AIChat {
2
+ id
3
+ summary
4
+ createdAt
5
+ updatedAt
6
+ }`;
7
+
8
+ export const aiChatMessageFragment = `fragment aiChatMessageFragment on AIChatMessage {
9
+ id
10
+ userId
11
+ cursor
12
+ text
13
+ photoUri
14
+ finished
15
+ at
16
+ }`;
@@ -0,0 +1,16 @@
1
+ import { gql } from 'graphql-tag';
2
+ import { aiChatFragment } from '../fragments/aiChatFragments';
3
+
4
+ export const startAIChatMtn = gql`
5
+ mutation startAIChat (
6
+ $text: String!
7
+ ) {
8
+ startAIChat (
9
+ text: $text
10
+ ) {
11
+ ...aiChatFragment
12
+ }
13
+ }
14
+
15
+ ${aiChatFragment}
16
+ `;
@@ -0,0 +1,41 @@
1
+ import { gql } from 'graphql-tag';
2
+ import { aiChatFragment, aiChatMessageFragment } from '../fragments/aiChatFragments';
3
+
4
+ export const aiChatQry = gql`
5
+ query aiChat (
6
+ $aiChatId: GenericID!
7
+ ) {
8
+ aiChat (
9
+ aiChatId: $aiChatId
10
+ ) {
11
+ ...aiChatFragment
12
+
13
+ messages {
14
+ ...aiChatMessageFragment
15
+ }
16
+ }
17
+ }
18
+
19
+ ${aiChatFragment}
20
+ ${aiChatMessageFragment}
21
+ `;
22
+
23
+ export const aiChatMessagesQry = gql`
24
+ query aiChatMessages (
25
+ $aiChatId: GenericID!
26
+ $cursor: Cursor
27
+ $after: Boolean!
28
+ $limit: Int!
29
+ ) {
30
+ aiChatMessages (
31
+ aiChatId: $aiChatId
32
+ cursor: $cursor
33
+ after: $after
34
+ limit: $limit
35
+ ) {
36
+ ...aiChatMessageFragment
37
+ }
38
+ }
39
+
40
+ ${aiChatMessageFragment}
41
+ `;
package/package.json CHANGED
@@ -1,38 +1,47 @@
1
1
  {
2
2
  "name": "@jsb188/graphql",
3
- "version": "1.0.1",
3
+ "version": "1.0.4",
4
4
  "description": "GraphQL client for react, using recoil",
5
5
  "license": "ISC",
6
6
  "author": "jsb188",
7
7
  "type": "module",
8
- "main": "main.ts",
9
8
  "types": "types.d.ts",
10
9
  "exports": {
11
- ".": "./main.ts",
12
10
  "./fragments/auth": "./gql/fragments/authFragments.ts",
11
+ "./fragments/aiChat": "./gql/fragments/aiChatFragments.ts",
13
12
  "./fragments/billing": "./gql/fragments/billingFragments.ts",
14
13
  "./fragments/card": "./gql/fragments/cardFragments.ts",
15
14
  "./fragments/chat": "./gql/fragments/chatFragments.ts",
16
15
  "./fragments/other": "./gql/fragments/otherFragments.ts",
17
16
  "./fragments/user": "./gql/fragments/userFragments.ts",
17
+ "./mutations/aiChat": "./gql/mutations/aiChatMutations.ts",
18
18
  "./mutations/auth": "./gql/mutations/authMutations.ts",
19
19
  "./mutations/billing": "./gql/mutations/billingMutations.ts",
20
20
  "./mutations/chat": "./gql/mutations/chatMutations.ts",
21
21
  "./mutations/other": "./gql/mutations/otherMutations.ts",
22
22
  "./mutations/user": "./gql/mutations/userMutations.ts",
23
+ "./queries/aiChat": "./gql/queries/aiChatQueries.ts",
23
24
  "./queries/auth": "./gql/queries/authQueries.ts",
24
25
  "./queries/billing": "./gql/queries/billingQueries.ts",
25
26
  "./queries/card": "./gql/queries/cardQueries.ts",
26
27
  "./queries/chat": "./gql/queries/chatQueries.ts",
27
28
  "./queries/other": "./gql/queries/otherQueries.ts",
28
29
  "./queries/user": "./gql/queries/userQueries.ts",
30
+ "./cache": "./cache/index.ts",
31
+ "./client": "./client/index.ts",
32
+ "./sse": "./sse.ts",
29
33
  "./types": "./types.d.ts",
30
- "./utils": "./cache/utils.ts"
34
+ "./utils": "./utils.ts"
31
35
  },
32
36
  "scripts": {
33
37
  "test": "echo \"Error: no test specified\" && exit 1"
34
38
  },
35
39
  "dependencies": {
40
+ "graphql": "^16.10.0",
36
41
  "graphql-tag": "^2.12.6"
42
+ },
43
+ "peerDependencies": {
44
+ "@jsb188/app": "^1.0.4",
45
+ "@jsb188/react": "^1.0.4"
37
46
  }
38
47
  }
package/sse.ts ADDED
@@ -0,0 +1,139 @@
1
+ import type { UpdateObserversFn } from './types.d';
2
+ import { loadFragment, updateQuery, updateFragment, addFragmentToCache } from './cache/';
3
+
4
+ /**
5
+ * Types
6
+ */
7
+
8
+ type ValidSSEType = (
9
+ // Default SSE events
10
+ 'CONNECTED' |
11
+ // Query handlers
12
+ 'QUERY_APPEND' | 'QUERY_PREPEND' |
13
+ // Fragment handlers
14
+ 'DATA_APPEND' | 'DATA_PREPEND' | 'DATA_UPDATE'
15
+ );
16
+
17
+ interface PublishPayload {
18
+ __type: ValidSSEType;
19
+ fragmentKey: string;
20
+ fragmentNamespace?: string;
21
+ dataFragmentKey?: string;
22
+ data: Record<string, any>;
23
+ }
24
+
25
+ /**
26
+ * Append or prepend data to a query
27
+ */
28
+
29
+ function handleQueryConcat(payload: PublishPayload, updateObservers?: UpdateObserversFn) {
30
+
31
+ const { __type, fragmentKey, fragmentNamespace, dataFragmentKey, data } = payload;
32
+ if (fragmentKey && fragmentNamespace && dataFragmentKey && data) {
33
+ const isAppend = __type === 'QUERY_APPEND';
34
+
35
+ const updateData = (currentData: any) => {
36
+ const currentList = currentData?.[fragmentNamespace]?.data;
37
+ if (
38
+ currentData?.[fragmentNamespace]?.__list &&
39
+ Array.isArray(currentList) &&
40
+ !currentList.find(a => a[0] === dataFragmentKey)
41
+ ) {
42
+ addFragmentToCache(dataFragmentKey, data);
43
+ const updatedList = isAppend ? [...currentList, [dataFragmentKey]] : [[dataFragmentKey], ...currentList];
44
+
45
+ return {
46
+ ...currentData,
47
+ [fragmentNamespace]: {
48
+ ...currentData?.[fragmentNamespace],
49
+ data: updatedList
50
+ }
51
+ };
52
+ }
53
+ return currentData;
54
+ }
55
+
56
+ updateQuery(
57
+ fragmentKey,
58
+ updateData,
59
+ false,
60
+ updateObservers
61
+ );
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Append or prepend data to a fragment
67
+ */
68
+
69
+ function handleFragmentConcat(payload: PublishPayload, updateObservers?: UpdateObserversFn) {
70
+ const { __type, fragmentKey, fragmentNamespace, data } = payload;
71
+ const isAppend = __type === 'DATA_APPEND';
72
+
73
+ if (fragmentKey && fragmentNamespace && data) {
74
+ const namespaceType = typeof fragmentNamespace;
75
+ const updateData = (currentData: any) => {
76
+ if (typeof currentData[fragmentNamespace] === namespaceType) {
77
+
78
+ let nextValue;
79
+ if (namespaceType === 'string') {
80
+ nextValue = isAppend ? `${currentData[fragmentNamespace]}${data}` : `${data}${currentData[fragmentNamespace]}`;
81
+ } else if (Array.isArray(currentData[fragmentNamespace])) {
82
+ nextValue = isAppend ? [...currentData[fragmentNamespace], data] : [data, ...currentData[fragmentNamespace]];
83
+ }
84
+
85
+ return {
86
+ ...currentData,
87
+ [fragmentNamespace]: nextValue
88
+ }
89
+ }
90
+ return currentData;
91
+ };
92
+
93
+ updateFragment(fragmentKey, updateData, null, isAppend, updateObservers);
94
+ }
95
+
96
+ }
97
+
98
+ /**
99
+ * Update data in a fragment
100
+ */
101
+
102
+ function handleFragmentUpdate(payload: PublishPayload, updateObservers?: UpdateObserversFn) {
103
+ const { fragmentKey, dataFragmentKey, data } = payload;
104
+ updateFragment(dataFragmentKey || fragmentKey, data, null, false, updateObservers);
105
+
106
+ console.log(
107
+ loadFragment(fragmentKey),
108
+ );
109
+
110
+ }
111
+
112
+ /**
113
+ * Data handler for SSE
114
+ */
115
+
116
+ function handleSSEData(payload: PublishPayload, updateObservers?: UpdateObserversFn) {
117
+
118
+ switch (payload.__type) {
119
+ case 'CONNECTED':
120
+ // Do nothing
121
+ break;
122
+ case 'QUERY_APPEND':
123
+ case 'QUERY_PREPEND':
124
+ handleQueryConcat(payload, updateObservers)
125
+ break;
126
+ case 'DATA_APPEND':
127
+ case 'DATA_PREPEND':
128
+ handleFragmentConcat(payload, updateObservers)
129
+ break;
130
+ case 'DATA_UPDATE':
131
+ handleFragmentUpdate(payload, updateObservers)
132
+ break;
133
+ default:
134
+ console.log('Unknown {__type} in handleSSEData():', payload.__type);
135
+ break;
136
+ }
137
+ }
138
+
139
+ export default handleSSEData;
package/types.d.ts CHANGED
@@ -1,18 +1,4 @@
1
-
2
- export interface ServerErrorObj {
3
- statusCode: number;
4
- errorCode: string;
5
- errorValue?: string;
6
- iconName?: string;
7
- title: string;
8
- message: string;
9
- }
10
-
11
- export interface SimpleErrorType {
12
- iconName?: string;
13
- title?: string;
14
- message: string;
15
- }
1
+ import type { ServerErrorObj, SimpleErrorType } from '@jsb188/app/types/app';
16
2
 
17
3
  export interface APIRequestOutput {
18
4
  aborted?: boolean;
@@ -26,19 +12,46 @@ export interface GraphQLHandlers {
26
12
  refetch: () => void;
27
13
  }
28
14
 
15
+ export interface UpdateDataObserverArgs {
16
+ queryId?: string | null;
17
+ fragmentIds?: (string | null)[];
18
+ forceRefetch?: boolean;
19
+ }
20
+
21
+ export type AnyModalPopUpFn = (data: any, err?: ServerErrorObj) => void;
29
22
  export type UpdateObserversFn = (args: UpdateDataObserverArgs) => void;
30
23
  export type OnCompletedGQLFn = (data: any, error: ServerErrorObj | null, variables: any) => void;
31
24
  export type OnErrorGQLFn = (error: ServerErrorObj | null, variables: any) => void;
32
25
 
33
- // Params for most GraphQL hooks
26
+ // GraphQL query hook options
27
+
28
+ export interface GraphQLQueryOptions {
29
+ name?: string;
30
+ eagerFragmentKeyMap?: any;
31
+ retryCount?: number;
32
+ variables?: Record<string, any> | null;
33
+ cacheMap?: any;
34
+ skip?: boolean;
35
+ testMode?: boolean;
36
+ openModalPopUp?: AnyModalPopUpFn | null;
37
+ onCompleted?: OnCompletedGQLFn
38
+ onError?: OnErrorGQLFn;
39
+ }
40
+
41
+ // Params for most GraphQL (query) hooks
42
+
43
+ export type UseQueryParams = Omit<GraphQLQueryOptions, 'name' | 'retryCount' | 'cacheMap'>;
34
44
 
35
- export type UseGraphQLParams = Partial<{
45
+ // Params for most GraphQL (mutation) hooks
46
+
47
+ export type UseMutationParams = Partial<{
36
48
  onCompleted: OnCompletedGQLFn;
37
49
  onError: OnErrorGQLFn;
38
50
  }>;
39
51
 
52
+
40
53
  // Params for most GraphQL hooks with these options
41
54
 
42
- export type UseGraphQLParamsExtra = Partial<{
55
+ export type UseMutationParamsExtra = Partial<{
43
56
  checkMountedBeforeCallback?: boolean;
44
- }> & UseGraphQLParams;
57
+ }> & UseMutationParams;
@@ -1,4 +1,5 @@
1
- import type { ServerErrorObj } from '../types.d';
1
+ import { getENVVariable } from '@jsb188/app';
2
+ import type { ServerErrorObj } from '@jsb188/app/types/app';
2
3
 
3
4
  const TIME_TRACKER = new Map();
4
5
 
@@ -54,3 +55,30 @@ export function isServerErrorGQL(apiResult: any): boolean {
54
55
  apiResult?.error?.errorCode === 'network_error'
55
56
  );
56
57
  }
58
+
59
+ /**
60
+ * Headers for all network requests
61
+ */
62
+
63
+ export function apiRequestHeaders(authorization: string | null | undefined): any {
64
+ const headers = {
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'),
69
+ // recaptcha: ? // Not sure if we're going to do this later any more
70
+ };
71
+
72
+ if (!getENVVariable('IS_BROWSER')) {
73
+ // @ts-expect-error Can't allow undefined or null
74
+ headers.ssr = '1';
75
+ }
76
+
77
+ 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
80
+ headers.authorization = authorization;
81
+ }
82
+
83
+ return headers;
84
+ }
package/main.ts DELETED
@@ -1,2 +0,0 @@
1
- export * from './cache/';
2
- export * from './cache/config';