@graphql-codegen/typescript-react-query 3.5.14-alpha-7a65ba05d.0 → 3.6.0-alpha-29eb1293b.0

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/index.mjs DELETED
@@ -1,584 +0,0 @@
1
- import { concatAST, Kind } from 'graphql';
2
- import { oldVisit } from '@graphql-codegen/plugin-helpers';
3
- import { parseMapper, buildMapperImport, ClientSideBaseVisitor, DocumentMode, getConfigValue } from '@graphql-codegen/visitor-plugin-common';
4
- import autoBind from 'auto-bind';
5
- import { pascalCase } from 'change-case-all';
6
- import { extname } from 'path';
7
-
8
- function generateQueryVariablesSignature(hasRequiredVariables, operationVariablesTypes) {
9
- return `variables${hasRequiredVariables ? '' : '?'}: ${operationVariablesTypes}`;
10
- }
11
- function generateInfiniteQueryKey(node, hasRequiredVariables) {
12
- if (hasRequiredVariables)
13
- return `['${node.name.value}.infinite', variables]`;
14
- return `variables === undefined ? ['${node.name.value}.infinite'] : ['${node.name.value}.infinite', variables]`;
15
- }
16
- function generateInfiniteQueryKeyMaker(node, operationName, operationVariablesTypes, hasRequiredVariables) {
17
- const signature = generateQueryVariablesSignature(hasRequiredVariables, operationVariablesTypes);
18
- return `\nuseInfinite${operationName}.getKey = (${signature}) => ${generateInfiniteQueryKey(node, hasRequiredVariables)};\n`;
19
- }
20
- function generateQueryKey(node, hasRequiredVariables) {
21
- if (hasRequiredVariables)
22
- return `['${node.name.value}', variables]`;
23
- return `variables === undefined ? ['${node.name.value}'] : ['${node.name.value}', variables]`;
24
- }
25
- function generateQueryKeyMaker(node, operationName, operationVariablesTypes, hasRequiredVariables) {
26
- const signature = generateQueryVariablesSignature(hasRequiredVariables, operationVariablesTypes);
27
- return `\nuse${operationName}.getKey = (${signature}) => ${generateQueryKey(node, hasRequiredVariables)};\n`;
28
- }
29
- function generateMutationKey(node) {
30
- return `['${node.name.value}']`;
31
- }
32
- function generateMutationKeyMaker(node, operationName) {
33
- return `\nuse${operationName}.getKey = () => ${generateMutationKey(node)};\n`;
34
- }
35
-
36
- class CustomMapperFetcher {
37
- constructor(visitor, customFetcher) {
38
- this.visitor = visitor;
39
- if (typeof customFetcher === 'string') {
40
- customFetcher = { func: customFetcher };
41
- }
42
- this._mapper = parseMapper(customFetcher.func);
43
- this._isReactHook = customFetcher.isReactHook;
44
- }
45
- getFetcherFnName(operationResultType, operationVariablesTypes) {
46
- return `${this._mapper.type}<${operationResultType}, ${operationVariablesTypes}>`;
47
- }
48
- generateFetcherImplementaion() {
49
- if (this._mapper.isExternal) {
50
- return buildMapperImport(this._mapper.source, [
51
- {
52
- identifier: this._mapper.type,
53
- asDefault: this._mapper.default,
54
- },
55
- ], this.visitor.config.useTypeImports);
56
- }
57
- return null;
58
- }
59
- generateInfiniteQueryHook(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables) {
60
- const variables = `variables${hasRequiredVariables ? '' : '?'}: ${operationVariablesTypes}`;
61
- const hookConfig = this.visitor.queryMethodMap;
62
- this.visitor.reactQueryHookIdentifiersInUse.add(hookConfig.infiniteQuery.hook);
63
- this.visitor.reactQueryOptionsIdentifiersInUse.add(hookConfig.infiniteQuery.options);
64
- const options = `options?: ${hookConfig.infiniteQuery.options}<${operationResultType}, TError, TData>`;
65
- const typedFetcher = this.getFetcherFnName(operationResultType, operationVariablesTypes);
66
- const implHookOuter = this._isReactHook ? `const query = ${typedFetcher}(${documentVariableName})` : '';
67
- const impl = this._isReactHook
68
- ? `(metaData) => query({...variables, ...(metaData.pageParam ?? {})})`
69
- : `(metaData) => ${typedFetcher}(${documentVariableName}, {...variables, ...(metaData.pageParam ?? {})})()`;
70
- return `export const useInfinite${operationName} = <
71
- TData = ${operationResultType},
72
- TError = ${this.visitor.config.errorType}
73
- >(
74
- ${variables},
75
- ${options}
76
- ) =>{
77
- ${implHookOuter}
78
- return ${hookConfig.infiniteQuery.hook}<${operationResultType}, TError, TData>(
79
- ${generateInfiniteQueryKey(node, hasRequiredVariables)},
80
- ${impl},
81
- options
82
- )};`;
83
- }
84
- generateQueryHook(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables) {
85
- const variables = `variables${hasRequiredVariables ? '' : '?'}: ${operationVariablesTypes}`;
86
- const hookConfig = this.visitor.queryMethodMap;
87
- this.visitor.reactQueryHookIdentifiersInUse.add(hookConfig.query.hook);
88
- this.visitor.reactQueryOptionsIdentifiersInUse.add(hookConfig.query.options);
89
- const options = `options?: ${hookConfig.query.options}<${operationResultType}, TError, TData>`;
90
- const typedFetcher = this.getFetcherFnName(operationResultType, operationVariablesTypes);
91
- const impl = this._isReactHook
92
- ? `${typedFetcher}(${documentVariableName}).bind(null, variables)`
93
- : `${typedFetcher}(${documentVariableName}, variables)`;
94
- return `export const use${operationName} = <
95
- TData = ${operationResultType},
96
- TError = ${this.visitor.config.errorType}
97
- >(
98
- ${variables},
99
- ${options}
100
- ) =>
101
- ${hookConfig.query.hook}<${operationResultType}, TError, TData>(
102
- ${generateQueryKey(node, hasRequiredVariables)},
103
- ${impl},
104
- options
105
- );`;
106
- }
107
- generateMutationHook(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables) {
108
- const variables = `variables?: ${operationVariablesTypes}`;
109
- const hookConfig = this.visitor.queryMethodMap;
110
- this.visitor.reactQueryHookIdentifiersInUse.add(hookConfig.mutation.hook);
111
- this.visitor.reactQueryOptionsIdentifiersInUse.add(hookConfig.mutation.options);
112
- const options = `options?: ${hookConfig.mutation.options}<${operationResultType}, TError, ${operationVariablesTypes}, TContext>`;
113
- const typedFetcher = this.getFetcherFnName(operationResultType, operationVariablesTypes);
114
- const impl = this._isReactHook
115
- ? `${typedFetcher}(${documentVariableName})`
116
- : `(${variables}) => ${typedFetcher}(${documentVariableName}, variables)()`;
117
- return `export const use${operationName} = <
118
- TError = ${this.visitor.config.errorType},
119
- TContext = unknown
120
- >(${options}) =>
121
- ${hookConfig.mutation.hook}<${operationResultType}, TError, ${operationVariablesTypes}, TContext>(
122
- ${generateMutationKey(node)},
123
- ${impl},
124
- options
125
- );`;
126
- }
127
- generateFetcherFetch(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables) {
128
- // We can't generate a fetcher field since we can't call react hooks outside of a React Fucntion Component
129
- // Related: https://reactjs.org/docs/hooks-rules.html
130
- if (this._isReactHook)
131
- return '';
132
- const variables = `variables${hasRequiredVariables ? '' : '?'}: ${operationVariablesTypes}`;
133
- const typedFetcher = this.getFetcherFnName(operationResultType, operationVariablesTypes);
134
- const impl = `${typedFetcher}(${documentVariableName}, variables, options)`;
135
- return `\nuse${operationName}.fetcher = (${variables}, options?: RequestInit['headers']) => ${impl};`;
136
- }
137
- }
138
-
139
- class FetchFetcher {
140
- constructor(visitor) {
141
- this.visitor = visitor;
142
- }
143
- generateFetcherImplementaion() {
144
- return `
145
- function fetcher<TData, TVariables>(endpoint: string, requestInit: RequestInit, query: string, variables?: TVariables) {
146
- return async (): Promise<TData> => {
147
- const res = await fetch(endpoint, {
148
- method: 'POST',
149
- ...requestInit,
150
- body: JSON.stringify({ query, variables }),
151
- });
152
-
153
- const json = await res.json();
154
-
155
- if (json.errors) {
156
- const { message } = json.errors[0];
157
-
158
- throw new Error(message);
159
- }
160
-
161
- return json.data;
162
- }
163
- }`;
164
- }
165
- generateInfiniteQueryHook(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables) {
166
- const variables = generateQueryVariablesSignature(hasRequiredVariables, operationVariablesTypes);
167
- const hookConfig = this.visitor.queryMethodMap;
168
- this.visitor.reactQueryHookIdentifiersInUse.add(hookConfig.infiniteQuery.hook);
169
- this.visitor.reactQueryOptionsIdentifiersInUse.add(hookConfig.infiniteQuery.options);
170
- const options = `options?: ${hookConfig.query.options}<${operationResultType}, TError, TData>`;
171
- return `export const useInfinite${operationName} = <
172
- TData = ${operationResultType},
173
- TError = ${this.visitor.config.errorType}
174
- >(
175
- dataSource: { endpoint: string, fetchParams?: RequestInit },
176
- pageParamKey: keyof ${operationVariablesTypes},
177
- ${variables},
178
- ${options}
179
- ) =>
180
- ${hookConfig.infiniteQuery.hook}<${operationResultType}, TError, TData>(
181
- ${generateInfiniteQueryKey(node, hasRequiredVariables)},
182
- (metaData) => fetcher<${operationResultType}, ${operationVariablesTypes}>(dataSource.endpoint, dataSource.fetchParams || {}, ${documentVariableName}, {...variables, ...(metaData.pageParam ?? {})})(),
183
- options
184
- );`;
185
- }
186
- generateQueryHook(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables) {
187
- const variables = generateQueryVariablesSignature(hasRequiredVariables, operationVariablesTypes);
188
- const hookConfig = this.visitor.queryMethodMap;
189
- this.visitor.reactQueryHookIdentifiersInUse.add(hookConfig.query.hook);
190
- this.visitor.reactQueryOptionsIdentifiersInUse.add(hookConfig.query.options);
191
- const options = `options?: ${hookConfig.query.options}<${operationResultType}, TError, TData>`;
192
- return `export const use${operationName} = <
193
- TData = ${operationResultType},
194
- TError = ${this.visitor.config.errorType}
195
- >(
196
- dataSource: { endpoint: string, fetchParams?: RequestInit },
197
- ${variables},
198
- ${options}
199
- ) =>
200
- ${hookConfig.query.hook}<${operationResultType}, TError, TData>(
201
- ${generateQueryKey(node, hasRequiredVariables)},
202
- fetcher<${operationResultType}, ${operationVariablesTypes}>(dataSource.endpoint, dataSource.fetchParams || {}, ${documentVariableName}, variables),
203
- options
204
- );`;
205
- }
206
- generateMutationHook(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables) {
207
- const variables = `variables?: ${operationVariablesTypes}`;
208
- const hookConfig = this.visitor.queryMethodMap;
209
- this.visitor.reactQueryHookIdentifiersInUse.add(hookConfig.mutation.hook);
210
- this.visitor.reactQueryOptionsIdentifiersInUse.add(hookConfig.mutation.options);
211
- const options = `options?: ${hookConfig.mutation.options}<${operationResultType}, TError, ${operationVariablesTypes}, TContext>`;
212
- return `export const use${operationName} = <
213
- TError = ${this.visitor.config.errorType},
214
- TContext = unknown
215
- >(
216
- dataSource: { endpoint: string, fetchParams?: RequestInit },
217
- ${options}
218
- ) =>
219
- ${hookConfig.mutation.hook}<${operationResultType}, TError, ${operationVariablesTypes}, TContext>(
220
- ${generateMutationKey(node)},
221
- (${variables}) => fetcher<${operationResultType}, ${operationVariablesTypes}>(dataSource.endpoint, dataSource.fetchParams || {}, ${documentVariableName}, variables)(),
222
- options
223
- );`;
224
- }
225
- generateFetcherFetch(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables) {
226
- const variables = generateQueryVariablesSignature(hasRequiredVariables, operationVariablesTypes);
227
- return `\nuse${operationName}.fetcher = (dataSource: { endpoint: string, fetchParams?: RequestInit }, ${variables}) => fetcher<${operationResultType}, ${operationVariablesTypes}>(dataSource.endpoint, dataSource.fetchParams || {}, ${documentVariableName}, variables);`;
228
- }
229
- }
230
-
231
- class GraphQLRequestClientFetcher {
232
- constructor(visitor) {
233
- this.visitor = visitor;
234
- }
235
- generateFetcherImplementaion() {
236
- return `
237
- function fetcher<TData, TVariables>(client: GraphQLClient, query: string, variables?: TVariables, headers?: RequestInit['headers']) {
238
- return async (): Promise<TData> => client.request<TData, TVariables>(query, variables, headers);
239
- }`;
240
- }
241
- generateInfiniteQueryHook(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables) {
242
- const variables = generateQueryVariablesSignature(hasRequiredVariables, operationVariablesTypes);
243
- const typeImport = this.visitor.config.useTypeImports ? 'import type' : 'import';
244
- this.visitor.imports.add(`${typeImport} { GraphQLClient } from 'graphql-request';`);
245
- const hookConfig = this.visitor.queryMethodMap;
246
- this.visitor.reactQueryHookIdentifiersInUse.add(hookConfig.infiniteQuery.hook);
247
- this.visitor.reactQueryOptionsIdentifiersInUse.add(hookConfig.infiniteQuery.options);
248
- const options = `options?: ${hookConfig.infiniteQuery.options}<${operationResultType}, TError, TData>`;
249
- return `export const useInfinite${operationName} = <
250
- TData = ${operationResultType},
251
- TError = ${this.visitor.config.errorType}
252
- >(
253
- pageParamKey: keyof ${operationVariablesTypes},
254
- client: GraphQLClient,
255
- ${variables},
256
- ${options},
257
- headers?: RequestInit['headers']
258
- ) =>
259
- ${hookConfig.infiniteQuery.hook}<${operationResultType}, TError, TData>(
260
- ${generateInfiniteQueryKey(node, hasRequiredVariables)},
261
- (metaData) => fetcher<${operationResultType}, ${operationVariablesTypes}>(client, ${documentVariableName}, {...variables, ...(metaData.pageParam ?? {})}, headers)(),
262
- options
263
- );`;
264
- }
265
- generateQueryHook(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables) {
266
- const variables = generateQueryVariablesSignature(hasRequiredVariables, operationVariablesTypes);
267
- const typeImport = this.visitor.config.useTypeImports ? 'import type' : 'import';
268
- this.visitor.imports.add(`${typeImport} { GraphQLClient } from 'graphql-request';`);
269
- this.visitor.imports.add(`${typeImport} { RequestInit } from 'graphql-request/dist/types.dom';`);
270
- const hookConfig = this.visitor.queryMethodMap;
271
- this.visitor.reactQueryHookIdentifiersInUse.add(hookConfig.query.hook);
272
- this.visitor.reactQueryOptionsIdentifiersInUse.add(hookConfig.query.options);
273
- const options = `options?: ${hookConfig.query.options}<${operationResultType}, TError, TData>`;
274
- return `export const use${operationName} = <
275
- TData = ${operationResultType},
276
- TError = ${this.visitor.config.errorType}
277
- >(
278
- client: GraphQLClient,
279
- ${variables},
280
- ${options},
281
- headers?: RequestInit['headers']
282
- ) =>
283
- ${hookConfig.query.hook}<${operationResultType}, TError, TData>(
284
- ${generateQueryKey(node, hasRequiredVariables)},
285
- fetcher<${operationResultType}, ${operationVariablesTypes}>(client, ${documentVariableName}, variables, headers),
286
- options
287
- );`;
288
- }
289
- generateMutationHook(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables) {
290
- const variables = `variables?: ${operationVariablesTypes}`;
291
- const typeImport = this.visitor.config.useTypeImports ? 'import type' : 'import';
292
- this.visitor.imports.add(`${typeImport} { GraphQLClient } from 'graphql-request';`);
293
- const hookConfig = this.visitor.queryMethodMap;
294
- this.visitor.reactQueryHookIdentifiersInUse.add(hookConfig.mutation.hook);
295
- this.visitor.reactQueryOptionsIdentifiersInUse.add(hookConfig.mutation.options);
296
- const options = `options?: ${hookConfig.mutation.options}<${operationResultType}, TError, ${operationVariablesTypes}, TContext>`;
297
- return `export const use${operationName} = <
298
- TError = ${this.visitor.config.errorType},
299
- TContext = unknown
300
- >(
301
- client: GraphQLClient,
302
- ${options},
303
- headers?: RequestInit['headers']
304
- ) =>
305
- ${hookConfig.mutation.hook}<${operationResultType}, TError, ${operationVariablesTypes}, TContext>(
306
- ${generateMutationKey(node)},
307
- (${variables}) => fetcher<${operationResultType}, ${operationVariablesTypes}>(client, ${documentVariableName}, variables, headers)(),
308
- options
309
- );`;
310
- }
311
- generateFetcherFetch(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables) {
312
- const variables = generateQueryVariablesSignature(hasRequiredVariables, operationVariablesTypes);
313
- const typeImport = this.visitor.config.useTypeImports ? 'import type' : 'import';
314
- this.visitor.imports.add(`${typeImport} { RequestInit } from 'graphql-request/dist/types.dom';`);
315
- return `\nuse${operationName}.fetcher = (client: GraphQLClient, ${variables}, headers?: RequestInit['headers']) => fetcher<${operationResultType}, ${operationVariablesTypes}>(client, ${documentVariableName}, variables, headers);`;
316
- }
317
- }
318
-
319
- class HardcodedFetchFetcher {
320
- constructor(visitor, config) {
321
- this.visitor = visitor;
322
- this.config = config;
323
- }
324
- getEndpoint() {
325
- try {
326
- new URL(this.config.endpoint);
327
- return JSON.stringify(this.config.endpoint);
328
- }
329
- catch (e) {
330
- return `${this.config.endpoint} as string`;
331
- }
332
- }
333
- getFetchParams() {
334
- let fetchParamsPartial = '';
335
- if (this.config.fetchParams) {
336
- const fetchParamsString = typeof this.config.fetchParams === 'string' ? this.config.fetchParams : JSON.stringify(this.config.fetchParams);
337
- fetchParamsPartial = `\n ...(${fetchParamsString}),`;
338
- }
339
- return ` method: "POST",${fetchParamsPartial}`;
340
- }
341
- generateFetcherImplementaion() {
342
- return `
343
- function fetcher<TData, TVariables>(query: string, variables?: TVariables) {
344
- return async (): Promise<TData> => {
345
- const res = await fetch(${this.getEndpoint()}, {
346
- ${this.getFetchParams()}
347
- body: JSON.stringify({ query, variables }),
348
- });
349
-
350
- const json = await res.json();
351
-
352
- if (json.errors) {
353
- const { message } = json.errors[0];
354
-
355
- throw new Error(message);
356
- }
357
-
358
- return json.data;
359
- }
360
- }`;
361
- }
362
- generateInfiniteQueryHook(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables) {
363
- const variables = generateQueryVariablesSignature(hasRequiredVariables, operationVariablesTypes);
364
- const hookConfig = this.visitor.queryMethodMap;
365
- this.visitor.reactQueryHookIdentifiersInUse.add(hookConfig.infiniteQuery.hook);
366
- this.visitor.reactQueryOptionsIdentifiersInUse.add(hookConfig.infiniteQuery.options);
367
- const options = `options?: ${hookConfig.infiniteQuery.options}<${operationResultType}, TError, TData>`;
368
- return `export const useInfinite${operationName} = <
369
- TData = ${operationResultType},
370
- TError = ${this.visitor.config.errorType}
371
- >(
372
- pageParamKey: keyof ${operationVariablesTypes},
373
- ${variables},
374
- ${options}
375
- ) =>
376
- ${hookConfig.infiniteQuery.hook}<${operationResultType}, TError, TData>(
377
- ${generateInfiniteQueryKey(node, hasRequiredVariables)},
378
- (metaData) => fetcher<${operationResultType}, ${operationVariablesTypes}>(${documentVariableName}, {...variables, ...(metaData.pageParam ?? {})})(),
379
- options
380
- );`;
381
- }
382
- generateQueryHook(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables) {
383
- const variables = generateQueryVariablesSignature(hasRequiredVariables, operationVariablesTypes);
384
- const hookConfig = this.visitor.queryMethodMap;
385
- this.visitor.reactQueryHookIdentifiersInUse.add(hookConfig.query.hook);
386
- this.visitor.reactQueryOptionsIdentifiersInUse.add(hookConfig.query.options);
387
- const options = `options?: ${hookConfig.query.options}<${operationResultType}, TError, TData>`;
388
- return `export const use${operationName} = <
389
- TData = ${operationResultType},
390
- TError = ${this.visitor.config.errorType}
391
- >(
392
- ${variables},
393
- ${options}
394
- ) =>
395
- ${hookConfig.query.hook}<${operationResultType}, TError, TData>(
396
- ${generateQueryKey(node, hasRequiredVariables)},
397
- fetcher<${operationResultType}, ${operationVariablesTypes}>(${documentVariableName}, variables),
398
- options
399
- );`;
400
- }
401
- generateMutationHook(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables) {
402
- const variables = `variables?: ${operationVariablesTypes}`;
403
- const hookConfig = this.visitor.queryMethodMap;
404
- this.visitor.reactQueryHookIdentifiersInUse.add(hookConfig.mutation.hook);
405
- this.visitor.reactQueryOptionsIdentifiersInUse.add(hookConfig.mutation.options);
406
- const options = `options?: ${hookConfig.mutation.options}<${operationResultType}, TError, ${operationVariablesTypes}, TContext>`;
407
- return `export const use${operationName} = <
408
- TError = ${this.visitor.config.errorType},
409
- TContext = unknown
410
- >(${options}) =>
411
- ${hookConfig.mutation.hook}<${operationResultType}, TError, ${operationVariablesTypes}, TContext>(
412
- ${generateMutationKey(node)},
413
- (${variables}) => fetcher<${operationResultType}, ${operationVariablesTypes}>(${documentVariableName}, variables)(),
414
- options
415
- );`;
416
- }
417
- generateFetcherFetch(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables) {
418
- const variables = generateQueryVariablesSignature(hasRequiredVariables, operationVariablesTypes);
419
- return `\nuse${operationName}.fetcher = (${variables}) => fetcher<${operationResultType}, ${operationVariablesTypes}>(${documentVariableName}, variables);`;
420
- }
421
- }
422
-
423
- class ReactQueryVisitor extends ClientSideBaseVisitor {
424
- constructor(schema, fragments, rawConfig, documents) {
425
- super(schema, fragments, rawConfig, {
426
- documentMode: DocumentMode.string,
427
- errorType: getConfigValue(rawConfig.errorType, 'unknown'),
428
- exposeDocument: getConfigValue(rawConfig.exposeDocument, false),
429
- exposeQueryKeys: getConfigValue(rawConfig.exposeQueryKeys, false),
430
- exposeMutationKeys: getConfigValue(rawConfig.exposeMutationKeys, false),
431
- exposeFetcher: getConfigValue(rawConfig.exposeFetcher, false),
432
- addInfiniteQuery: getConfigValue(rawConfig.addInfiniteQuery, false),
433
- });
434
- this.rawConfig = rawConfig;
435
- this.reactQueryHookIdentifiersInUse = new Set();
436
- this.reactQueryOptionsIdentifiersInUse = new Set();
437
- this.queryMethodMap = {
438
- infiniteQuery: {
439
- hook: 'useInfiniteQuery',
440
- options: 'UseInfiniteQueryOptions',
441
- },
442
- query: {
443
- hook: 'useQuery',
444
- options: 'UseQueryOptions',
445
- },
446
- mutation: {
447
- hook: 'useMutation',
448
- options: 'UseMutationOptions',
449
- },
450
- };
451
- this._externalImportPrefix = this.config.importOperationTypesFrom ? `${this.config.importOperationTypesFrom}.` : '';
452
- this._documents = documents;
453
- this.fetcher = this.createFetcher(rawConfig.fetcher || 'fetch');
454
- autoBind(this);
455
- }
456
- get imports() {
457
- return this._imports;
458
- }
459
- createFetcher(raw) {
460
- if (raw === 'fetch') {
461
- return new FetchFetcher(this);
462
- }
463
- if (typeof raw === 'object' && 'endpoint' in raw) {
464
- return new HardcodedFetchFetcher(this, raw);
465
- }
466
- if (raw === 'graphql-request') {
467
- return new GraphQLRequestClientFetcher(this);
468
- }
469
- return new CustomMapperFetcher(this, raw);
470
- }
471
- get hasOperations() {
472
- return this._collectedOperations.length > 0;
473
- }
474
- getImports() {
475
- const baseImports = super.getImports();
476
- if (!this.hasOperations) {
477
- return baseImports;
478
- }
479
- if (this.config.addInfiniteQuery) {
480
- this.reactQueryOptionsIdentifiersInUse.add('QueryFunctionContext');
481
- }
482
- const hookAndTypeImports = [
483
- ...Array.from(this.reactQueryHookIdentifiersInUse),
484
- ...Array.from(this.reactQueryOptionsIdentifiersInUse).map(identifier => `${this.config.useTypeImports ? 'type ' : ''}${identifier}`),
485
- ];
486
- return [...baseImports, `import { ${hookAndTypeImports.join(', ')} } from 'react-query';`];
487
- }
488
- getFetcherImplementation() {
489
- return this.fetcher.generateFetcherImplementaion();
490
- }
491
- _getHookSuffix(name, operationType) {
492
- if (this.config.omitOperationSuffix) {
493
- return '';
494
- }
495
- if (!this.config.dedupeOperationSuffix) {
496
- return pascalCase(operationType);
497
- }
498
- if (name.includes('Query') || name.includes('Mutation') || name.includes('Subscription')) {
499
- return '';
500
- }
501
- return pascalCase(operationType);
502
- }
503
- buildOperation(node, documentVariableName, operationType, operationResultType, operationVariablesTypes, hasRequiredVariables) {
504
- var _a, _b;
505
- const nodeName = (_b = (_a = node.name) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : '';
506
- const suffix = this._getHookSuffix(nodeName, operationType);
507
- const operationName = this.convertName(nodeName, {
508
- suffix,
509
- useTypesPrefix: false,
510
- useTypesSuffix: false,
511
- });
512
- operationResultType = this._externalImportPrefix + operationResultType;
513
- operationVariablesTypes = this._externalImportPrefix + operationVariablesTypes;
514
- if (operationType === 'Query') {
515
- let query = this.fetcher.generateQueryHook(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables);
516
- if (this.config.exposeDocument) {
517
- query += `\nuse${operationName}.document = ${documentVariableName};\n`;
518
- }
519
- if (this.config.exposeQueryKeys) {
520
- query += `\n${generateQueryKeyMaker(node, operationName, operationVariablesTypes, hasRequiredVariables)};\n`;
521
- }
522
- if (this.config.addInfiniteQuery) {
523
- query += `\n${this.fetcher.generateInfiniteQueryHook(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables)}\n`;
524
- if (this.config.exposeQueryKeys) {
525
- query += `\n${generateInfiniteQueryKeyMaker(node, operationName, operationVariablesTypes, hasRequiredVariables)};\n`;
526
- }
527
- }
528
- // The reason we're looking at the private field of the CustomMapperFetcher to see if it's a react hook
529
- // is to prevent calling generateFetcherFetch for each query since all the queries won't be able to generate
530
- // a fetcher field anyways.
531
- if (this.config.exposeFetcher && !this.fetcher._isReactHook) {
532
- query += this.fetcher.generateFetcherFetch(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables);
533
- }
534
- return query;
535
- }
536
- if (operationType === 'Mutation') {
537
- let query = this.fetcher.generateMutationHook(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables);
538
- if (this.config.exposeMutationKeys) {
539
- query += generateMutationKeyMaker(node, operationName);
540
- }
541
- if (this.config.exposeFetcher && !this.fetcher._isReactHook) {
542
- query += this.fetcher.generateFetcherFetch(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables);
543
- }
544
- return query;
545
- }
546
- if (operationType === 'Subscription') {
547
- // eslint-disable-next-line no-console
548
- console.warn(`Plugin "typescript-react-query" does not support GraphQL Subscriptions at the moment! Ignoring "${node.name.value}"...`);
549
- }
550
- return null;
551
- }
552
- }
553
-
554
- const plugin = (schema, documents, config) => {
555
- const allAst = concatAST(documents.map(v => v.document));
556
- const allFragments = [
557
- ...allAst.definitions.filter(d => d.kind === Kind.FRAGMENT_DEFINITION).map(fragmentDef => ({
558
- node: fragmentDef,
559
- name: fragmentDef.name.value,
560
- onType: fragmentDef.typeCondition.name.value,
561
- isExternal: false,
562
- })),
563
- ...(config.externalFragments || []),
564
- ];
565
- const visitor = new ReactQueryVisitor(schema, allFragments, config, documents);
566
- const visitorResult = oldVisit(allAst, { leave: visitor });
567
- if (visitor.hasOperations) {
568
- return {
569
- prepend: [...visitor.getImports(), visitor.getFetcherImplementation()],
570
- content: [visitor.fragments, ...visitorResult.definitions.filter(t => typeof t === 'string')].join('\n'),
571
- };
572
- }
573
- return {
574
- prepend: [...visitor.getImports()],
575
- content: [visitor.fragments, ...visitorResult.definitions.filter(t => typeof t === 'string')].join('\n'),
576
- };
577
- };
578
- const validate = async (schema, documents, config, outputFile) => {
579
- if (extname(outputFile) !== '.ts' && extname(outputFile) !== '.tsx') {
580
- throw new Error(`Plugin "typescript-react-query" requires extension to be ".ts" or ".tsx"!`);
581
- }
582
- };
583
-
584
- export { ReactQueryVisitor, plugin, validate };