-
-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathuseLazyQuery.ts
More file actions
218 lines (196 loc) · 5.51 KB
/
Copy pathuseLazyQuery.ts
File metadata and controls
218 lines (196 loc) · 5.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import {
GQtyError,
type BaseGeneratedSchema,
type GQtyClient,
type RetryOptions,
} from 'gqty';
import * as React from 'react';
import {
translateFetchPolicy,
type LegacyFetchPolicy,
type OnErrorHandler,
} from '../common';
import type { ReactClientOptionsWithDefaults } from '../utils';
export type LazyFetchPolicy = Exclude<LegacyFetchPolicy, 'cache-first'>;
export interface UseLazyQueryOptions<TData> {
onCompleted?: (data: TData) => void;
onError?: OnErrorHandler;
fetchPolicy?: LazyFetchPolicy;
retry?: RetryOptions;
suspense?: boolean;
operationName?: string;
/** Custom GraphQL extensions to be exposed to the query fetcher. */
extensions?: Record<string, unknown>;
}
export interface UseLazyQueryState<TData> {
data: TData | undefined;
error?: GQtyError;
isLoading: boolean;
isCalled: boolean;
promise?: Promise<TData>;
}
type UseLazyQueryReducerAction<TData> =
| { type: 'cache-found'; data: TData }
| { type: 'success'; data: TData }
| { type: 'failure'; error: GQtyError }
| { type: 'loading'; promise: Promise<TData> };
function UseLazyQueryReducer<TData>(
state: UseLazyQueryState<TData>,
action: UseLazyQueryReducerAction<TData>
): UseLazyQueryState<TData> {
switch (action.type) {
case 'loading': {
if (state.isLoading) return state;
return {
data: state.data,
isLoading: true,
isCalled: true,
promise: action.promise,
};
}
case 'success': {
return {
data: action.data,
isLoading: false,
isCalled: true,
};
}
case 'failure': {
return {
data: state.data,
isLoading: false,
error: action.error,
isCalled: true,
};
}
case 'cache-found': {
return {
data: action.data,
isLoading: state.isLoading,
isCalled: true,
};
}
}
}
function InitUseLazyQueryReducer<TData>(): UseLazyQueryState<TData> {
return {
data: undefined,
isLoading: false,
isCalled: false,
};
}
export interface UseLazyQuery<GeneratedSchema extends BaseGeneratedSchema> {
<TData = unknown, TArgs = undefined>(
fn: (query: GeneratedSchema['query'], args: TArgs) => TData,
options?: UseLazyQueryOptions<TData>
): readonly [
(
...opts: undefined extends TArgs
? [
{
fn?: (query: GeneratedSchema['query'], args: TArgs) => TData;
args?: TArgs;
fetchPolicy?: LazyFetchPolicy;
operationName?: string;
}?,
]
: [
{
fn?: (query: GeneratedSchema['query'], args: TArgs) => TData;
args: TArgs;
fetchPolicy?: LazyFetchPolicy;
opertionName?: string;
},
]
) => Promise<TData>,
UseLazyQueryState<TData>,
];
}
export function createUseLazyQuery<TSchema extends BaseGeneratedSchema>(
{ resolve }: GQtyClient<TSchema>,
{
defaults: {
retry: defaultRetry,
lazyQuerySuspense: defaultSuspense,
lazyFetchPolicy: defaultFetchPolicy,
},
}: ReactClientOptionsWithDefaults
) {
const useLazyQuery: UseLazyQuery<TSchema> = (
fn,
{
onCompleted,
onError,
fetchPolicy: hookDefaultFetchPolicy = defaultFetchPolicy,
retry = defaultRetry,
suspense = defaultSuspense,
operationName: defaultOperationName,
extensions,
} = {}
) => {
type TCallback = typeof fn;
type TArgs = Parameters<TCallback>[1];
type TData = ReturnType<TCallback>;
type TCallbackArgs = {
fn?: TCallback;
args?: TArgs;
fetchPolicy?: LazyFetchPolicy;
operationName?: string;
};
const [state, dispatch] = React.useReducer(
UseLazyQueryReducer,
undefined,
InitUseLazyQueryReducer
) as [
UseLazyQueryState<TData>,
React.Dispatch<UseLazyQueryReducerAction<TData>>,
];
if (suspense) {
if (state.promise) throw state.promise;
if (state.error) throw state.error;
}
return React.useMemo(() => {
const fetchQuery = async ({
fn: resolveFn = fn,
args,
fetchPolicy = hookDefaultFetchPolicy,
operationName = defaultOperationName,
}: TCallbackArgs = {}) => {
let innerFetchPromise: Promise<TData> | undefined;
try {
const fetchPromise = resolve(
({ query }) => resolveFn(query, args as TArgs),
{
awaitsFetch: false,
cachePolicy: translateFetchPolicy(fetchPolicy),
onFetch(promise) {
innerFetchPromise = promise as Promise<TData>;
},
retryPolicy: retry,
operationName,
extensions,
}
).then((data) => {
const typedData = data as TData;
if (fetchPolicy === 'cache-and-network') {
dispatch({ type: 'cache-found', data: typedData });
}
return innerFetchPromise ?? typedData;
});
dispatch({ type: 'loading', promise: fetchPromise });
const data = await fetchPromise;
onCompleted?.(data);
dispatch({ type: 'success', data });
return data;
} catch (error) {
const typedError = GQtyError.create(error);
onError?.(typedError);
dispatch({ type: 'failure', error: typedError });
throw error;
}
};
return Object.freeze([fetchQuery, state]);
}, [fn, onCompleted, onError, retry, extensions]);
};
return useLazyQuery;
}