forked from orval-labs/orval
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery-generator.ts
More file actions
1227 lines (1117 loc) · 37.2 KB
/
Copy pathquery-generator.ts
File metadata and controls
1227 lines (1117 loc) · 37.2 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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
camel,
generateMutator,
type GeneratorImport,
type GeneratorMutator,
type GeneratorOptions,
type GeneratorVerbOptions,
type GetterBody,
type GetterParams,
type GetterProp,
type GetterProps,
GetterPropType,
type GetterQueryParam,
type GetterResponse,
jsDoc,
logWarning,
OutputClient,
type OutputClientFunc,
type OutputHttpClient,
pascal,
toObjectString,
Verbs,
} from '@orval/core';
import { getHookOptions, getQueryErrorType, getQueryOptions } from './client';
import type { FrameworkAdapter } from './framework-adapter';
import { generateMutationHook } from './mutation-generator';
import {
generateQueryOptions,
getQueryOptionsDefinition,
QueryType,
} from './query-options';
import { getHasSignal } from './utils';
/**
* Decide whether the current operation's configuration conflicts with a
* `mutationInvalidates` rule. The rule wires its invalidation through the
* Mutation hook's `onSuccess`, so referencing an operation that is not
* generated as a Mutation (either forced into a Query via per-operation
* `useQuery: true`, or suppressed entirely) makes the rule a silent no-op.
*
* Returns the warning message when the conflict applies, or `undefined`
* when the configuration is consistent.
*/
export const getMutationInvalidatesConflictWarning = ({
operationName,
isMutation,
isQuery,
mutationInvalidates,
}: {
operationName: string;
isMutation: boolean | undefined;
isQuery: boolean;
mutationInvalidates:
| NonNullable<
GeneratorVerbOptions['override']['query']['mutationInvalidates']
>
| undefined;
}): string | undefined => {
if (isMutation) return undefined;
if (!mutationInvalidates?.length) return undefined;
const referencingRule = mutationInvalidates.find((rule) =>
rule.onMutations.includes(operationName),
);
if (!referencingRule) return undefined;
const generatedAs = isQuery ? 'Query hook' : 'plain function (no hook)';
return (
`mutationInvalidates rule references '${operationName}', but that ` +
`operation is generated as a ${generatedAs}, not a Mutation. The ` +
`invalidation will not fire. Either remove '${operationName}' from the ` +
`rule's onMutations list, or configure '${operationName}' so that it ` +
`is generated as a Mutation hook.`
);
};
const escapeRegExpMetaChars = (value: string): string =>
value.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
/**
* Wraps the body parameter's type in a property string with the mutator's
* `BodyType<T>` envelope so that user-facing Query helpers (hook signature,
* `getXxxQueryOptions`, `getXxxQueryKey`, prefetch / invalidate / set+get
* QueryData) match the request function's signature, which is already
* wrapped by `client.ts`. Without this, callers that pass a plain body to
* a non-GET Query hook (possible after #2376 routes non-GET verbs to
* Query hooks) would hit a type mismatch against the underlying request
* function.
*
* The pattern handles three prop shapes that the various
* `toObjectString(props, ...)` callers can emit:
* - `name: T` — required body
* - `name?: T` — optional body
* - `name: undefined | T` — `definedInitialData` overload transform
*
* `body.definition` is fully regex-escaped so types containing metachars
* (e.g. `Pet[]`, `Foo | Bar`, anonymous object types) are matched
* verbatim rather than reinterpreted as regex syntax.
*
* No-op when the operation has no body or the mutator does not export a
* `BodyType<T>` wrapper, so existing GET-only Query keys are unchanged.
*/
export const wrapPropsBodyWithMutatorBodyType = ({
propsString,
body,
mutator,
}: {
propsString: string;
body: GetterBody;
mutator: GeneratorMutator | undefined;
}): string => {
if (!mutator?.bodyTypeName || !body.definition) return propsString;
const bodyDefinitionPattern = escapeRegExpMetaChars(body.definition);
return propsString.replace(
new RegExp(
String.raw`(\w+\??:\s*(?:undefined\s*\|\s*)?)${bodyDefinitionPattern}`,
),
`$1${mutator.bodyTypeName}<${body.definition}>`,
);
};
/**
* Widens a parameter signature to be optional. Skips params that already
* carry a default value (`= ...`), since those are syntactically optional
* and adding `?` on top would be a TypeScript error.
*/
export const makeOptionalParam = (impl: string) => {
if (impl.includes('=')) return impl;
return impl.replace(/^(\w+):\s*/, '$1?: ');
};
/**
* Widens a parameter type to also accept `undefined`. Already-optional
* (`?:`) signatures are normalized to required-with-undefined, and params
* with a default value pass through unchanged.
*/
export const allowUndefinedParam = (impl: string) => {
if (impl.includes('=')) return impl;
const optional = /^(\w+)\?:\s*(.+)$/.exec(impl);
if (optional) return `${optional[1]}: ${optional[2]} | undefined`;
return impl.replace(/^(\w+):\s*(.+)$/, '$1: $2 | undefined');
};
/**
* Renders the `setXxxQueryData` helper as either a React hook (returns a
* setter) or a plain function taking `queryClient`. Both shapes share the
* same body and signature, so this collapses what would otherwise be two
* near-identical template literals.
*/
const renderSetQueryDataHelper = ({
doc,
isReactQuery,
fnName,
propsSig,
body,
}: {
doc: string | undefined;
isReactQuery: boolean;
fnName: string;
propsSig: string;
body: string;
}) => {
const docPrefix = doc ?? '';
if (isReactQuery) {
return `${docPrefix}export const ${fnName} = () => {
const queryClient = useQueryClient();
return (${propsSig}) => {
${body}
};
}\n`;
}
return `${docPrefix}export const ${fnName} = (queryClient: QueryClient, ${propsSig}) => {
${body}
}\n`;
};
/**
* Renders the prop list shared by `getXxxQueryKey`, `setXxxQueryData` and
* `getXxxQueryData` helpers: headers are dropped, path params stay required,
* non-path params (query params, body) are passed through `widenNonPath`
* (defaults to identity — pass `makeOptionalParam` or `allowUndefinedParam`
* to relax the signature).
*
* Centralising this prevents the three call sites from drifting apart on
* how they treat the same props.
*/
const buildKeyShapedProps = ({
props,
body,
mutator,
widenNonPath = (impl) => impl,
}: {
props: GetterProps;
body: GetterBody;
mutator: GeneratorMutator | undefined;
widenNonPath?: (impl: string) => string;
}) =>
wrapPropsBodyWithMutatorBodyType({
propsString: toObjectString(
props
.filter((prop) => prop.type !== GetterPropType.HEADER)
.map((prop) => ({
...prop,
implementation:
prop.type === GetterPropType.PARAM ||
prop.type === GetterPropType.NAMED_PATH_PARAMS
? prop.implementation
: widenNonPath(prop.implementation),
})),
'implementation',
),
body,
mutator,
});
/**
* Computes a verb prefix segment for query keys when a non-GET operation is
* routed to a Query hook. Without this prefix, two operations sharing a path
* (e.g. `GET /pets` and `POST /pets`) would generate cache keys that both
* begin with `'/pets'`, so TanStack Query would mix their cached data and
* `invalidateQueries({ queryKey: ['/pets'] })` would match both.
*
* Skipped for GET (preserves existing keys) and when
* `useOperationIdAsQueryKey` is enabled (operation IDs are already unique
* across verb + path, so the prefix would be redundant).
*
* Returns the uppercased verb when a prefix should be inserted, or
* `undefined` when no prefix is needed.
*/
export const getQueryKeyVerbPrefix = ({
verb,
useOperationIdAsQueryKey,
}: {
verb: Verbs;
useOperationIdAsQueryKey: boolean | undefined;
}): string | undefined => {
if (useOperationIdAsQueryKey) return undefined;
if (verb === Verbs.GET) return undefined;
return verb.toUpperCase();
};
const getQueryFnArguments = ({
hasQueryParam,
hasSignal,
hasSignalParam = false,
}: {
hasQueryParam: boolean;
hasSignal: boolean;
hasSignalParam?: boolean;
}) => {
if (!hasQueryParam && !hasSignal) {
return '';
}
// Rename AbortSignal if API has a param named "signal" to avoid conflict
const signalDestructure = hasSignalParam ? 'signal: querySignal' : 'signal';
if (hasQueryParam) {
if (hasSignal) {
return `{ ${signalDestructure}, pageParam }`;
}
return '{ pageParam }';
}
return `{ ${signalDestructure} }`;
};
const generatePrefetch = ({
usePrefetch,
type,
useQuery,
useInfinite,
operationName,
mutator,
doc,
queryProps,
dataType,
errorType,
queryArguments,
queryOptionsVarName,
queryOptionsFnName,
queryProperties,
isRequestOptions,
}: {
operationName: string;
mutator?: GeneratorMutator;
type: (typeof QueryType)[keyof typeof QueryType];
usePrefetch?: boolean;
useQuery?: boolean;
useInfinite?: boolean;
doc?: string;
queryProps: string;
dataType: string;
errorType: string;
queryArguments: string;
queryOptionsVarName: string;
queryOptionsFnName: string;
queryProperties: string;
isRequestOptions: boolean;
}) => {
const shouldGeneratePrefetch =
usePrefetch &&
(type === QueryType.QUERY ||
type === QueryType.INFINITE ||
(type === QueryType.SUSPENSE_QUERY && !useQuery) ||
(type === QueryType.SUSPENSE_INFINITE && !useInfinite));
if (!shouldGeneratePrefetch) {
return '';
}
const prefetchType =
type === QueryType.QUERY || type === QueryType.SUSPENSE_QUERY
? 'query'
: 'infinite-query';
const prefetchFnName = camel(`prefetch-${prefetchType}`);
if (mutator?.isHook) {
const prefetchVarName = camel(
`use-prefetch-${operationName}-${prefetchType}`,
);
return `${doc}export const ${prefetchVarName} = <TData = Awaited<ReturnType<${dataType}>>, TError = ${errorType}>(${queryProps} ${queryArguments}) => {
const queryClient = useQueryClient();
const ${queryOptionsVarName} = ${queryOptionsFnName}(${queryProperties}${
queryProperties ? ',' : ''
}${isRequestOptions ? 'options' : 'queryOptions'})
return useCallback(async (): Promise<QueryClient> => {
await queryClient.${prefetchFnName}(${queryOptionsVarName})
return queryClient;
},[queryClient, ${queryOptionsVarName}]);
};\n`;
} else {
const prefetchVarName = camel(`prefetch-${operationName}-${prefetchType}`);
return `${doc}export const ${prefetchVarName} = async <TData = Awaited<ReturnType<${dataType}>>, TError = ${errorType}>(\n queryClient: QueryClient, ${queryProps} ${queryArguments}\n ): Promise<QueryClient> => {
const ${queryOptionsVarName} = ${queryOptionsFnName}(${queryProperties}${
queryProperties ? ',' : ''
}${isRequestOptions ? 'options' : 'queryOptions'})
await queryClient.${prefetchFnName}(${queryOptionsVarName});
return queryClient;
}\n`;
}
};
const generateQueryImplementation = ({
queryOption: { name, queryParam, options, type, queryKeyFnName },
operationId,
operationName,
queryProperties,
queryKeyProperties,
queryParams,
params,
props,
body,
mutator,
queryOptionsMutator,
queryKeyMutator,
isRequestOptions,
response,
httpClient,
isExactOptionalPropertyTypes,
hasSignal,
useRuntimeFetcher,
route,
doc,
usePrefetch,
useQuery,
useInfinite,
useInvalidate,
useSetQueryData,
useGetQueryData,
adapter,
}: {
queryOption: {
name: string;
options?: object | boolean;
type: (typeof QueryType)[keyof typeof QueryType];
queryParam?: string;
queryKeyFnName: string;
};
isRequestOptions: boolean;
operationId: string;
operationName: string;
queryProperties: string;
queryKeyProperties: string;
params: GetterParams;
props: GetterProps;
body: GetterBody;
response: GetterResponse;
queryParams?: GetterQueryParam;
mutator?: GeneratorMutator;
queryOptionsMutator?: GeneratorMutator;
queryKeyMutator?: GeneratorMutator;
httpClient: OutputHttpClient;
isExactOptionalPropertyTypes: boolean;
hasSignal: boolean;
useRuntimeFetcher?: boolean;
route: string;
doc?: string;
usePrefetch?: boolean;
useQuery?: boolean;
useInfinite?: boolean;
useInvalidate?: boolean;
useSetQueryData?: boolean;
useGetQueryData?: boolean;
adapter: FrameworkAdapter;
}) => {
const {
hasQueryV5,
hasQueryV5WithDataTagError,
hasQueryV5WithInfiniteQueryOptionsError,
} = adapter;
// Check if API has a param named "signal" to avoid conflict with AbortSignal
const hasSignalParam = props.some(
(prop: GetterProp) => prop.name === 'signal',
);
const queryPropDefinitions = wrapPropsBodyWithMutatorBodyType({
propsString: toObjectString(props, 'definition'),
body,
mutator,
});
const definedInitialDataQueryPropsDefinitions =
wrapPropsBodyWithMutatorBodyType({
propsString: toObjectString(
props.map((prop) => {
const regex = new RegExp(String.raw`^${prop.name}\s*\?:`);
if (!regex.test(prop.definition)) {
return prop;
}
const definitionWithUndefined = prop.definition.replace(
regex,
`${prop.name}: undefined | `,
);
return {
...prop,
definition: definitionWithUndefined,
};
}),
'definition',
),
body,
mutator,
});
const queryProps = wrapPropsBodyWithMutatorBodyType({
propsString: toObjectString(props, 'implementation'),
body,
mutator,
});
const hasInfiniteQueryParam = queryParam && queryParams?.schema.name;
const httpFunctionProps = queryParam
? adapter.getInfiniteQueryHttpProps(
props,
queryParam,
httpClient,
!!mutator,
)
: adapter.getHttpFunctionQueryProps(queryProperties, httpClient, !!mutator);
const definedInitialDataReturnType = adapter.getQueryReturnType({
type,
isMutatorHook: mutator?.isHook,
operationName,
hasQueryV5,
hasQueryV5WithDataTagError,
isInitialDataDefined: true,
});
const returnType = adapter.getQueryReturnType({
type,
isMutatorHook: mutator?.isHook,
operationName,
hasQueryV5,
hasQueryV5WithDataTagError,
});
const errorType = getQueryErrorType(
operationName,
response,
httpClient,
mutator,
);
const dataType = mutator?.isHook
? `ReturnType<typeof use${pascal(operationName)}Hook>`
: `typeof ${operationName}`;
const definedInitialDataQueryArguments = adapter.generateQueryArguments({
operationName,
mutator,
definitions: '',
isRequestOptions,
type,
queryParams,
queryParam,
initialData: 'defined',
httpClient,
useRuntimeFetcher,
});
const undefinedInitialDataQueryArguments = adapter.generateQueryArguments({
operationName,
definitions: '',
mutator,
isRequestOptions,
type,
queryParams,
queryParam,
initialData: 'undefined',
httpClient,
useRuntimeFetcher,
});
const queryArguments = adapter.generateQueryArguments({
operationName,
definitions: '',
mutator,
isRequestOptions,
type,
queryParams,
queryParam,
httpClient,
useRuntimeFetcher,
});
// Separate arguments for getQueryOptions function (includes http: HttpClient param for Angular)
const queryArgumentsForOptions = adapter.generateQueryArguments({
operationName,
definitions: '',
mutator,
isRequestOptions,
type,
queryParams,
queryParam,
httpClient,
forQueryOptions: true,
useRuntimeFetcher,
});
const queryOptions = getQueryOptions({
isRequestOptions,
isExactOptionalPropertyTypes,
mutator,
hasSignal,
httpClient,
hasSignalParam,
useRuntimeFetcher,
});
const hookOptions = getHookOptions({
isRequestOptions,
httpClient,
mutator,
useRuntimeFetcher,
});
const queryFnArguments = getQueryFnArguments({
hasQueryParam:
!!queryParam && props.some(({ type }) => type === 'queryParam'),
hasSignal,
hasSignalParam,
});
const queryOptionFnReturnType = getQueryOptionsDefinition({
operationName,
mutator,
definitions: '',
type,
prefix: adapter.getQueryOptionsDefinitionPrefix(),
hasQueryV5,
hasQueryV5WithInfiniteQueryOptionsError,
queryParams,
queryParam,
isReturnType: true,
adapter,
});
const queryOptionsImp = generateQueryOptions({
params,
options,
type,
adapter,
});
const queryOptionsFnName = camel(
queryKeyMutator || queryOptionsMutator || mutator?.isHook
? `use-${name}-queryOptions`
: `get-${name}-queryOptions`,
);
const queryOptionsVarName = isRequestOptions ? 'queryOptions' : 'options';
const hasParamReservedWord = props.some(
(prop: GetterProp) => prop.name === 'query',
);
const queryResultVarName = hasParamReservedWord ? '_query' : 'query';
const infiniteParam =
queryParams && queryParam
? `, ${queryParams.schema.name}['${queryParam}']`
: '';
const TData =
hasQueryV5 &&
(type === QueryType.INFINITE || type === QueryType.SUSPENSE_INFINITE)
? `InfiniteData<Awaited<ReturnType<${dataType}>>${infiniteParam}>`
: `Awaited<ReturnType<${dataType}>>`;
// For Angular, add http: HttpClient as FIRST param (required, before optional params)
// This avoids TS1016 "required param cannot follow optional param"
const httpFirstParam = adapter.getHttpFirstParam(mutator);
const queryOptionsFn = `export const ${queryOptionsFnName} = <TData = ${TData}, TError = ${errorType}>(${httpFirstParam}${queryProps} ${queryArgumentsForOptions}) => {
${hookOptions}
const queryKey = ${
queryKeyMutator
? `${queryKeyMutator.name}({ ${queryProperties} }${
queryKeyMutator.hasSecondArg
? `, { url: \`${route}\`, queryOptions }`
: ''
});`
: `${adapter.getQueryKeyPrefix()}${queryKeyFnName}(${queryKeyProperties});`
}
${
mutator?.isHook
? `const ${operationName} = use${pascal(operationName)}Hook();`
: ''
}
const queryFn: QueryFunction<Awaited<ReturnType<${
mutator?.isHook
? `ReturnType<typeof use${pascal(operationName)}Hook>`
: `typeof ${operationName}`
}>>${
hasQueryV5 && hasInfiniteQueryParam
? `, QueryKey, ${queryParams.schema.name}['${queryParam}']`
: ''
}> = (${queryFnArguments}) => ${operationName}(${httpFunctionProps}${
httpFunctionProps ? ', ' : ''
}${queryOptions});
${adapter.getUnrefStatements(props)}
${
queryOptionsMutator
? // Pass the same options object the non-mutator branch returns so
// generated guards (e.g. the `enabled` clause for nullish path
// params) reach the mutator instead of being dropped. See #1522.
// The third arg additionally carries operation identity (matching
// mutationOptions per #1974) so mutators can branch on the source
// operation. See #3153.
`const customOptions = ${
queryOptionsMutator.name
}({ queryKey, queryFn, ${queryOptionsImp}}${
queryOptionsMutator.hasSecondArg ? `, { ${queryProperties} }` : ''
}${
queryOptionsMutator.hasThirdArg
? `, { url: \`${route}\`, operationId: '${operationId}', operationName: '${operationName}' }`
: ''
});`
: ''
}
return ${
queryOptionsMutator
? 'customOptions'
: `{ queryKey, queryFn, ${queryOptionsImp}}`
}${
adapter.shouldCastQueryOptions?.() === false
? ''
: ` as ${queryOptionFnReturnType} ${
adapter.shouldAnnotateQueryKey()
? `& { queryKey: ${hasQueryV5 ? `DataTag<QueryKey, TData${hasQueryV5WithDataTagError ? ', TError' : ''}>` : 'QueryKey'} }`
: ''
}`
}
}`;
const operationPrefix = adapter.hookPrefix;
const optionalQueryClientArgument = adapter.getOptionalQueryClientArgument();
const queryHookName = camel(`${operationPrefix}-${name}`);
const overrideTypes = `
export function ${queryHookName}<TData = ${TData}, TError = ${errorType}>(\n ${definedInitialDataQueryPropsDefinitions} ${definedInitialDataQueryArguments} ${optionalQueryClientArgument}\n ): ${definedInitialDataReturnType}
export function ${queryHookName}<TData = ${TData}, TError = ${errorType}>(\n ${queryPropDefinitions} ${undefinedInitialDataQueryArguments} ${optionalQueryClientArgument}\n ): ${returnType}
export function ${queryHookName}<TData = ${TData}, TError = ${errorType}>(\n ${queryPropDefinitions} ${queryArguments} ${optionalQueryClientArgument}\n ): ${returnType}`;
const prefetchContext = {
usePrefetch,
type,
useQuery,
useInfinite,
operationName,
mutator,
queryProps,
dataType,
errorType,
queryArguments: queryArgumentsForOptions,
queryOptionsVarName,
queryOptionsFnName,
queryProperties,
isRequestOptions,
doc,
};
const prefetch = adapter.generatePrefetch
? adapter.generatePrefetch(prefetchContext)
: generatePrefetch(prefetchContext);
const isPrimaryQueryType =
type === QueryType.QUERY ||
type === QueryType.INFINITE ||
(type === QueryType.SUSPENSE_QUERY && !useQuery) ||
(type === QueryType.SUSPENSE_INFINITE && !useInfinite);
const buildBaseQueryKeyExpr = () =>
queryKeyMutator
? `${queryKeyMutator.name}({ ${queryProperties} }${
queryKeyMutator.hasSecondArg ? `, { url: \`${route}\` }` : ''
})`
: `${queryKeyFnName}(${queryKeyProperties})`;
// queryOptions mutator may augment the queryKey (e.g. tenant prefix).
// Route invalidate / set / get helpers through the mutator so the key
// matches what the query hook actually wrote into the cache. Hook-shaped
// mutators are skipped here because none of these helpers can legally
// call a hook at the right time — set/get helpers stop being emitted
// entirely in that case (see `hasHookMutator` below), and invalidate
// falls back to the unmutated base key for backwards compatibility.
const applyQueryOptionsMutator = (baseExpr: string) =>
queryOptionsMutator && !queryOptionsMutator.isHook
? `${queryOptionsMutator.name}({ queryKey: ${baseExpr} }${
queryOptionsMutator.hasSecondArg ? `, { ${queryProperties} }` : ''
}${
queryOptionsMutator.hasThirdArg
? `, { url: \`${route}\`, operationId: '${operationId}', operationName: '${operationName}' }`
: ''
}).queryKey`
: baseExpr;
// Hook-shaped queryOptions mutators rewrite the queryKey at hook-call
// time, but the set/get helpers cannot call a hook to recover that key.
// Emitting them would silently target a different cache slot than the
// query hook actually wrote into, so we skip generation in that case and
// surface a warning to the user. Invalidate is left alone for backwards
// compatibility — it has shipped with the same gap and changing its
// contract is out of scope here.
const hasHookMutator = !!queryOptionsMutator?.isHook;
if (hasHookMutator && (useSetQueryData || useGetQueryData)) {
logWarning(
`'${name}' has a hook-based queryOptions mutator, so the requested set/get-query-data helpers were skipped to avoid a cache-key mismatch with the query hook.`,
);
}
const shouldGenerateInvalidate = useInvalidate && isPrimaryQueryType;
const invalidateFnName = camel(`invalidate-${name}`);
const invalidateQueryKeyExpr = applyQueryOptionsMutator(
buildBaseQueryKeyExpr(),
);
const shouldGenerateSetQueryData =
useSetQueryData && isPrimaryQueryType && !hasHookMutator;
const isReactQuery = adapter.outputClient === OutputClient.REACT_QUERY;
const setQueryDataFnName = isReactQuery
? camel(`use-set-${name}-query-data`)
: camel(`set-${name}-query-data`);
// Route the set-query-data key through the same mutator as invalidate so
// that any user-applied prefix (e.g. tenant) is honoured. Without this,
// `setQueriesData` and `invalidateQueries` would target different keys.
const setQueryDataKeyExpr = applyQueryOptionsMutator(buildBaseQueryKeyExpr());
// `setQueriesData` matches by query-key prefix, so non-path props (query
// params, body) are widened to `T | undefined` — passing `undefined`
// updates every cached entry sharing the path prefix, matching what
// `getXxxQueryKey()` already allows. `T | undefined` is used instead of
// `?:` because the `updater` parameter follows and TS1016 forbids a
// required parameter after an optional one.
const setQueryDataProps = buildKeyShapedProps({
props,
body,
mutator,
widenNonPath: allowUndefinedParam,
});
const shouldGenerateGetQueryData =
useGetQueryData && isPrimaryQueryType && !hasHookMutator;
const getQueryDataFnName = isReactQuery
? camel(`use-get-${name}-query-data`)
: camel(`get-${name}-query-data`);
// `getQueryData` reads a single cache entry — keep every prop required and
// reuse `setQueryDataKeyExpr` so read and write target the same slot.
const getQueryDataProps = buildKeyShapedProps({ props, body, mutator });
// Generate query init (e.g. const queryOptions = fn(...) or const http = inject(HttpClient))
const queryInit = adapter.generateQueryInit({
queryOptionsFnName,
queryProperties,
isRequestOptions,
mutator,
});
// Generate query hook invocation arguments
const queryInvocationArgs = adapter.generateQueryInvocationArgs({
props,
queryOptionsFnName,
queryProperties,
isRequestOptions,
mutator,
operationPrefix,
type,
queryOptionsVarName,
optionalQueryClientArgument,
});
const queryInvocationSuffix = adapter.getQueryInvocationSuffix();
return `
${queryOptionsFn}
export type ${pascal(
name,
)}QueryResult = NonNullable<Awaited<ReturnType<${dataType}>>>
export type ${pascal(name)}QueryError = ${errorType}
${adapter.shouldGenerateOverrideTypes() ? overrideTypes : ''}
${doc}
export function ${queryHookName}<TData = ${TData}, TError = ${errorType}>(\n ${wrapPropsBodyWithMutatorBodyType(
{
propsString: adapter.getHookPropsDefinitions(props),
body,
mutator,
},
)} ${queryArguments} ${optionalQueryClientArgument} \n ): ${returnType} {
${queryInit}
const ${queryResultVarName} = ${camel(
`${operationPrefix}-${adapter.getQueryType(type)}`,
)}(${queryInvocationArgs}${queryInvocationSuffix})${adapter.shouldCastQueryResult?.() === false ? '' : ` as ${returnType}`};
${adapter.getQueryReturnStatement({
hasQueryV5,
hasQueryV5WithDataTagError,
queryResultVarName,
queryOptionsVarName,
})}
}\n
${prefetch}
${
shouldGenerateInvalidate
? `${doc}export const ${invalidateFnName} = async (\n queryClient: QueryClient, ${queryProps} options?: InvalidateOptions\n ): Promise<QueryClient> => {
await queryClient.invalidateQueries({ queryKey: ${invalidateQueryKeyExpr} }, options);
return queryClient;
}\n`
: ''
}
${
shouldGenerateSetQueryData
? renderSetQueryDataHelper({
doc,
isReactQuery,
fnName: setQueryDataFnName,
propsSig: `${setQueryDataProps}updater: ${TData} | undefined | ((old: ${TData} | undefined) => ${TData} | undefined)`,
body: `queryClient.setQueriesData<${TData}>({ queryKey: ${setQueryDataKeyExpr} }, updater);`,
})
: ''
}
${
shouldGenerateGetQueryData
? isReactQuery
? `${doc}export const ${getQueryDataFnName} = () => {
const queryClient = useQueryClient();
return (${getQueryDataProps}) =>
queryClient.getQueryData<${TData}>(${setQueryDataKeyExpr});
}\n`
: `${doc}export const ${getQueryDataFnName} = (queryClient: QueryClient, ${getQueryDataProps}) =>
queryClient.getQueryData<${TData}>(${setQueryDataKeyExpr});\n`
: ''
}
`;
};
export const generateQueryHook = async (
verbOptions: GeneratorVerbOptions,
options: GeneratorOptions,
outputClient: OutputClient | OutputClientFunc,
adapter?: FrameworkAdapter,
) => {
if (!adapter) {
throw new Error('FrameworkAdapter is required for generateQueryHook');
}
const {
queryParams,
operationName,
body,
props: _props,
verb,
params,
override,
mutator,
response,
operationId,
summary,
deprecated,
} = verbOptions;
const {
route,
override: { operations },
context,
output,
} = options;
// Use adapter to transform props (Vue wraps with MaybeRef)
const props = adapter.transformProps(_props);
const query = override.query;
const isRequestOptions = override.requestOptions !== false;
const operationQueryOptions = operations[operationId]?.query;
const isExactOptionalPropertyTypes =
!!context.output.tsconfig?.compilerOptions?.exactOptionalPropertyTypes;
const httpClient = context.output.httpClient;
const doc = jsDoc({ summary, deprecated });
let implementation = '';
let mutators: GeneratorMutator[] | undefined;
// Precedence: per-operation override > global > per-verb default.
// `?? false` lets per-op `false` actually disable a globally enabled
// hook (the previous `[…].some(Boolean)` masked op-level false).
const effectiveUseQuery =
operationQueryOptions?.useQuery ??
override.query.useQuery ??
verb === Verbs.GET;
const effectiveUseMutation =
operationQueryOptions?.useMutation ??
override.query.useMutation ??
verb !== Verbs.GET;
// Suspense / Infinite have no per-verb default; global is GET-only,
// per-op overrides bypass that restriction in either direction.
const globalSuspenseOrInfiniteOnlyForGet = (
flag: boolean | undefined,
): boolean => flag === true && verb === Verbs.GET;
const effectiveUseSuspenseQuery =
operationQueryOptions?.useSuspenseQuery ??
globalSuspenseOrInfiniteOnlyForGet(override.query.useSuspenseQuery);
const effectiveUseInfinite =
operationQueryOptions?.useInfinite ??
globalSuspenseOrInfiniteOnlyForGet(override.query.useInfinite);
const effectiveUseSuspenseInfiniteQuery =
operationQueryOptions?.useSuspenseInfiniteQuery ??
globalSuspenseOrInfiniteOnlyForGet(override.query.useSuspenseInfiniteQuery);
let isQuery =
effectiveUseQuery ||
effectiveUseSuspenseQuery ||
effectiveUseInfinite ||
effectiveUseSuspenseInfiniteQuery;
// No verb gate here: `effectiveUseMutation` already encodes the
// per-verb default (`verb !== Verbs.GET`), so an explicit
// `useMutation: true` — global or per-operation — must be honoured for
// GET operations too, mirroring how `isQuery` honours `useQuery: true`
// for non-GET verbs (#3358).
let isMutation = effectiveUseMutation;
// If both query and mutation are true for a non-GET operation, prioritize query
if (verb !== Verbs.GET && isQuery) {
isMutation = false;
}
// If both query and mutation are true for a GET operation, prioritize mutation
if (verb === Verbs.GET && isMutation) {
isQuery = false;
}
// Warn when an operation referenced by a `mutationInvalidates` rule's
// `onMutations` list is generated as a Query (or no hook at all). The rule
// is wired up in mutation-generator and only fires for Mutation hooks, so
// referencing a Query-emitted operation is a silent no-op — surface that
// misconfiguration explicitly.
const conflictWarning = getMutationInvalidatesConflictWarning({
operationName,
isMutation,
isQuery,
mutationInvalidates: override.query.mutationInvalidates,
});
if (conflictWarning) {
logWarning(conflictWarning);