forked from orval-labs/orval
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
780 lines (700 loc) 路 22.3 KB
/
Copy pathclient.ts
File metadata and controls
780 lines (700 loc) 路 22.3 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
import {
type ClientHeaderBuilder,
generateFormDataAndUrlEncodedFunction,
generateMutatorConfig,
generateMutatorRequestOptions,
generateOptions,
type GeneratorDependency,
type GeneratorMutator,
type GeneratorOptions,
type GeneratorVerbOptions,
getAngularFilteredParamsCallExpression,
getAngularFilteredParamsHelperBody,
getSuccessResponseType,
type GetterResponse,
isObject,
isSyntheticDefaultImportsAllow,
kebab,
makeRouteSafe,
OutputHttpClient,
pascal,
toObjectString,
} from '@orval/core';
import {
generateFetchHeader,
generateRequestFunction as generateFetchRequestFunction,
} from '@orval/fetch';
import { getHasSignal, vueUnRefParams, vueWrapTypeWithMaybeRef } from './utils';
export const AXIOS_DEPENDENCIES = [
{
exports: [
{
name: 'axios',
default: true,
values: true,
syntheticDefaultImport: true,
},
{ name: 'AxiosRequestConfig' },
{ name: 'AxiosResponse' },
{ name: 'AxiosError' },
],
dependency: 'axios',
},
] as const satisfies readonly GeneratorDependency[];
export const ANGULAR_HTTP_DEPENDENCIES = [
{
exports: [
{ name: 'HttpClient', values: true },
{ name: 'HttpHeaders', values: true },
{ name: 'HttpParams', values: true },
{ name: 'HttpContext' },
],
dependency: '@angular/common/http',
},
// Note: 'inject' from @angular/core is already in ANGULAR_QUERY_DEPENDENCIES
{
exports: [
{ name: 'lastValueFrom', values: true },
{ name: 'fromEvent', values: true },
],
dependency: 'rxjs',
},
{
exports: [
{ name: 'takeUntil', values: true },
{ name: 'map', values: true },
],
dependency: 'rxjs/operators',
},
] as const satisfies readonly GeneratorDependency[];
export const generateQueryRequestFunction = (
verbOptions: GeneratorVerbOptions,
options: GeneratorOptions,
isVue: boolean,
isAngularClient = false,
) => {
if (
isAngularClient ||
options.context.output.httpClient === OutputHttpClient.ANGULAR
) {
return generateAngularHttpRequestFunction(verbOptions, options);
}
return options.context.output.httpClient === OutputHttpClient.AXIOS
? generateAxiosRequestFunction(verbOptions, options, isVue)
: generateFetchRequestFunction(verbOptions, options);
};
export const generateAngularHttpRequestFunction = (
{
headers,
queryParams,
operationName,
response,
mutator,
body,
props,
verb,
formData,
formUrlEncoded,
override,
}: GeneratorVerbOptions,
{ route, context }: GeneratorOptions,
) => {
const isRequestOptions = override.requestOptions !== false;
const isFormData = !override.formData.disabled;
const isFormUrlEncoded = override.formUrlEncoded !== false;
const hasSignal = getHasSignal({
overrideQuerySignal: override.query.signal,
});
// Check if API has a param named "signal" to avoid conflict with AbortSignal
const hasSignalParam = props.some((prop) => prop.name === 'signal');
const bodyForm = generateFormDataAndUrlEncodedFunction({
formData,
formUrlEncoded,
body,
isFormData,
isFormUrlEncoded,
});
// Handle mutator case
if (mutator) {
const isExactOptionalPropertyTypes =
!!context.output.tsconfig?.compilerOptions?.exactOptionalPropertyTypes;
const mutatorConfig = generateMutatorConfig({
route,
body,
headers,
queryParams,
response,
verb,
isFormData,
isFormUrlEncoded,
hasSignal,
hasSignalParam,
isExactOptionalPropertyTypes,
isVue: false,
isAngular: context.output.httpClient === OutputHttpClient.ANGULAR,
});
const requestOptions = isRequestOptions
? generateMutatorRequestOptions(
override.requestOptions,
mutator.hasSecondArg,
)
: '';
const propsImplementation = toObjectString(props, 'implementation');
return `${override.query.shouldExportHttpClient ? 'export ' : ''}const ${operationName} = (\n ${propsImplementation}\n ${
isRequestOptions && mutator.hasSecondArg
? `options${context.output.optionsParamRequired ? '' : '?'}: SecondParameter<typeof ${mutator.name}>,`
: ''
} ${getSignalDefinition({ hasSignal, hasSignalParam })}) => {
${bodyForm}
return ${mutator.name}<${response.definition.success || 'unknown'}>(
${mutatorConfig},
${requestOptions});
}
`;
}
// Generate native Angular HttpClient implementation
const queryProps = toObjectString(props, 'implementation').replace(
/,\s*$/,
'',
);
const dataType = response.definition.success || 'unknown';
// Build URL with query params - use httpParams to avoid shadowing the 'params' variable
const hasQueryParams = queryParams?.schema.name;
// The queryParams variable from function props is always named 'params'
const filteredParamsExpression = getAngularFilteredParamsCallExpression(
'params',
queryParams?.requiredNullableKeys,
);
const urlConstruction = hasQueryParams
? `const httpParams = params ? new HttpParams({ fromObject: ${filteredParamsExpression} }) : undefined;
const url = \`${route}\`;`
: `const url = \`${route}\`;`;
// Build request options
const httpOptions: string[] = [];
if (hasQueryParams) {
httpOptions.push('params: httpParams');
}
if (headers) {
httpOptions.push('headers: new HttpHeaders(headers)');
}
// Use only success response content types to determine responseType
// (response.contentTypes includes error responses which may be JSON and would
// incorrectly prevent text/blob responseType from being set)
const successResponseType = getSuccessResponseType(response);
const responseTypeOption = successResponseType
? `'${successResponseType}'`
: undefined;
if (responseTypeOption) {
httpOptions.push(`responseType: ${responseTypeOption}`);
}
const optionsStr =
httpOptions.length > 0 ? `, { ${httpOptions.join(', ')} }` : '';
// Build the HTTP method call
let httpCall: string;
const httpGeneric = responseTypeOption ? '' : `<${dataType}>`;
const bodyArg =
isFormData && body.formData
? 'formData'
: isFormUrlEncoded && body.formUrlEncoded
? 'formUrlEncoded'
: body.definition
? toObjectString([body], 'implementation').replace(/,\s*$/, '')
: '';
switch (verb) {
case 'get':
case 'head': {
httpCall = `http.${verb}${httpGeneric}(url${optionsStr})`;
break;
}
case 'delete': {
httpCall = bodyArg
? `http.${verb}${httpGeneric}(url, { ${httpOptions.length > 0 ? httpOptions.join(', ') + ', ' : ''}body: ${bodyArg} })`
: `http.${verb}${httpGeneric}(url${optionsStr})`;
break;
}
default: {
// post, put, patch
httpCall = `http.${verb}${httpGeneric}(url, ${bodyArg || 'undefined'}${optionsStr})`;
break;
}
}
// Detect if Zod runtime validation should be applied
const responseType = response.definition.success;
const isPrimitiveType = [
'string',
'number',
'boolean',
'void',
'unknown',
].includes(responseType);
const hasSchema = response.imports.some((imp) => imp.name === responseType);
const isZodOutput =
isObject(context.output.schemas) && context.output.schemas.type === 'zod';
const isValidateResponse =
override.query.runtimeValidation &&
isZodOutput &&
!isPrimitiveType &&
hasSchema;
// If validation is enabled, pipe through map(data => Schema.parse(data))
if (isValidateResponse) {
const schemaValueRef =
responseType === 'Error' ? 'ErrorSchema' : responseType;
httpCall = `${httpCall}.pipe(map(data => ${schemaValueRef}.parse(data)))`;
}
// For Angular, we use takeUntil with fromEvent to handle AbortSignal cancellation
// This follows the pattern from TanStack Query Angular documentation
// Note: signal can be null (from RequestInit), so we accept null | undefined
const optionsParam = hasSignal
? 'options?: { signal?: AbortSignal | null }'
: '';
// Build additional params after http, handling empty queryProps properly
const additionalParams = [queryProps, optionsParam]
.filter(Boolean)
.join(', ');
// Note: http parameter is passed from the inject* function which has injection context
return `${override.query.shouldExportHttpClient ? 'export ' : ''}const ${operationName} = (
http: HttpClient${additionalParams ? `,\n ${additionalParams}` : ''}
): Promise<${dataType}> => {
${bodyForm}
${urlConstruction}
const request$ = ${httpCall};
if (options?.signal) {
return lastValueFrom(request$.pipe(takeUntil(fromEvent(options.signal, 'abort'))));
}
return lastValueFrom(request$);
}
`;
};
export const generateAxiosRequestFunction = (
{
headers,
queryParams,
operationName,
response,
mutator,
body,
props: _props,
verb,
formData,
formUrlEncoded,
override,
paramsSerializer,
}: GeneratorVerbOptions,
{ route: _route, context }: GeneratorOptions,
isVue: boolean,
) => {
let props = _props;
let route = _route;
if (isVue) {
props = vueWrapTypeWithMaybeRef(_props);
}
if (context.output.urlEncodeParameters) {
route = makeRouteSafe(route);
}
const isRequestOptions = override.requestOptions !== false;
const isFormData = !override.formData.disabled;
const isFormUrlEncoded = override.formUrlEncoded !== false;
const hasSignal = getHasSignal({
overrideQuerySignal: override.query.signal,
});
// Check if API has a param named "signal" to avoid conflict with AbortSignal
const hasSignalParam = _props.some((prop) => prop.name === 'signal');
const isExactOptionalPropertyTypes =
!!context.output.tsconfig?.compilerOptions?.exactOptionalPropertyTypes;
const bodyForm = generateFormDataAndUrlEncodedFunction({
formData,
formUrlEncoded,
body,
isFormData,
isFormUrlEncoded,
});
if (mutator) {
const mutatorConfig = generateMutatorConfig({
route,
body,
headers,
queryParams,
response,
verb,
isFormData,
isFormUrlEncoded,
hasSignal,
hasSignalParam,
isExactOptionalPropertyTypes,
isVue,
});
const bodyDefinition = body.definition.replace('[]', String.raw`\[\]`);
const propsImplementation =
mutator.bodyTypeName && body.definition
? toObjectString(props, 'implementation').replace(
new RegExp(String.raw`(\w*):\s?${bodyDefinition}`),
`$1: ${mutator.bodyTypeName}<${body.definition}>`,
)
: toObjectString(props, 'implementation');
const requestOptions = isRequestOptions
? generateMutatorRequestOptions(
override.requestOptions,
mutator.hasSecondArg,
)
: '';
if (mutator.isHook) {
const ret = `${
override.query.shouldExportMutatorHooks ? 'export ' : ''
}const use${pascal(operationName)}Hook = () => {
const ${operationName} = ${mutator.name}<${
response.definition.success || 'unknown'
}>();
return useCallback((\n ${propsImplementation}\n ${
isRequestOptions && mutator.hasSecondArg
? `options${context.output.optionsParamRequired ? '' : '?'}: SecondParameter<ReturnType<typeof ${mutator.name}>>,`
: ''
}${getSignalDefinition({ hasSignal, hasSignalParam })}) => {${bodyForm}
return ${operationName}(
${mutatorConfig},
${requestOptions});
}, [${operationName}])
}
`;
const vueRet = `${
override.query.shouldExportMutatorHooks ? 'export ' : ''
}const use${pascal(operationName)}Hook = () => {
const ${operationName} = ${mutator.name}<${
response.definition.success || 'unknown'
}>();
return (\n ${propsImplementation}\n ${
isRequestOptions && mutator.hasSecondArg
? `options${context.output.optionsParamRequired ? '' : '?'}: SecondParameter<ReturnType<typeof ${mutator.name}>>,`
: ''
}${getSignalDefinition({ hasSignal, hasSignalParam })}) => {${bodyForm}
return ${operationName}(
${mutatorConfig},
${requestOptions});
}
}
`;
return isVue ? vueRet : ret;
}
return `${override.query.shouldExportHttpClient ? 'export ' : ''}const ${operationName} = (\n ${propsImplementation}\n ${
isRequestOptions && mutator.hasSecondArg
? `options${context.output.optionsParamRequired ? '' : '?'}: SecondParameter<typeof ${mutator.name}>,`
: ''
}${getSignalDefinition({ hasSignal, hasSignalParam })}) => {
${isVue ? vueUnRefParams(props) : ''}
${bodyForm}
return ${mutator.name}<${response.definition.success || 'unknown'}>(
${mutatorConfig},
${requestOptions});
}
`;
}
const isSyntheticDefaultImportsAllowed = isSyntheticDefaultImportsAllow(
context.output.tsconfig,
);
const options = generateOptions({
route,
body,
headers,
queryParams,
response,
verb,
requestOptions: override.requestOptions,
isFormData,
isFormUrlEncoded,
paramsSerializer,
paramsSerializerOptions: override.paramsSerializerOptions,
isExactOptionalPropertyTypes,
hasSignal,
hasSignalParam,
isVue: isVue,
});
const optionsArgs = generateRequestOptionsArguments({
isRequestOptions,
hasSignal,
hasSignalParam,
});
const queryProps = toObjectString(props, 'implementation');
const httpRequestFunctionImplementation = `${override.query.shouldExportHttpClient ? 'export ' : ''}const ${operationName} = (\n ${queryProps} ${optionsArgs} ): Promise<AxiosResponse<${
response.definition.success || 'unknown'
}>> => {
${isVue ? vueUnRefParams(props) : ''}
${bodyForm}
return axios${
isSyntheticDefaultImportsAllowed ? '' : '.default'
}.${verb}(${options});
}
`;
return httpRequestFunctionImplementation;
};
export const generateRequestOptionsArguments = ({
isRequestOptions,
hasSignal,
hasSignalParam = false,
}: {
isRequestOptions: boolean;
hasSignal: boolean;
hasSignalParam?: boolean;
}) => {
if (isRequestOptions) {
return 'options?: AxiosRequestConfig\n';
}
return getSignalDefinition({ hasSignal, hasSignalParam });
};
export const getSignalDefinition = ({
hasSignal,
hasSignalParam = false,
}: {
hasSignal: boolean;
hasSignalParam?: boolean;
}): string => {
if (!hasSignal) {
return '';
}
const signalVar = hasSignalParam ? 'querySignal' : 'signal';
return `${signalVar}?: AbortSignal\n`;
};
export const getQueryArgumentsRequestType = (
httpClient: OutputHttpClient,
mutator?: GeneratorMutator,
useRuntimeFetcher?: boolean,
) => {
if (!mutator) {
if (httpClient === OutputHttpClient.AXIOS) {
return `axios?: AxiosRequestConfig`;
}
if (httpClient === OutputHttpClient.FETCH && useRuntimeFetcher) {
return 'fetch?: RequestInit, fetcher?: typeof globalThis.fetch';
}
return 'fetch?: RequestInit';
}
if (mutator.hasSecondArg && !mutator.isHook) {
return `request?: SecondParameter<typeof ${mutator.name}>`;
}
if (mutator.hasSecondArg && mutator.isHook) {
return `request?: SecondParameter<ReturnType<typeof ${mutator.name}>>`;
}
return '';
};
export const getQueryOptions = ({
isRequestOptions,
mutator,
isExactOptionalPropertyTypes,
hasSignal,
httpClient,
hasSignalParam = false,
useRuntimeFetcher = false,
}: {
isRequestOptions: boolean;
mutator?: GeneratorMutator;
isExactOptionalPropertyTypes: boolean;
hasSignal: boolean;
httpClient: OutputHttpClient;
hasSignalParam?: boolean;
useRuntimeFetcher?: boolean;
}) => {
// Use querySignal if API has a param named "signal" to avoid conflict
const signalVar = hasSignalParam ? 'querySignal' : 'signal';
// Only use explicit `signal: querySignal` when there's a naming conflict
const signalProp = hasSignalParam ? `signal: ${signalVar}` : 'signal';
if (!mutator && isRequestOptions) {
const options =
httpClient === OutputHttpClient.AXIOS ? 'axiosOptions' : 'fetchOptions';
const fetcherArg =
httpClient === OutputHttpClient.FETCH && useRuntimeFetcher
? ', fetcherFn'
: '';
if (!hasSignal) {
return `${options}${fetcherArg}`;
}
return `{ ${
isExactOptionalPropertyTypes
? `...(${signalVar} ? { ${signalProp} } : {})`
: signalProp
}, ...${options} }${fetcherArg}`;
}
// For Angular mutators with hasSecondArg, pass http through options parameter
// http is injected in the queryOptionsFn and passed here as the second arg to the mutator
if (mutator?.hasSecondArg && httpClient === OutputHttpClient.ANGULAR) {
if (!hasSignal) {
return 'http';
}
return `http, ${signalVar}`;
}
if (mutator?.hasSecondArg && isRequestOptions) {
if (!hasSignal) {
return 'requestOptions';
}
// Axios and Angular mutators: signal is a separate argument
// Fetch mutators: signal is wrapped in options object
return httpClient === OutputHttpClient.AXIOS ||
httpClient === OutputHttpClient.ANGULAR
? `requestOptions, ${signalVar}`
: `{ ${signalProp}, ...requestOptions }`;
}
if (hasSignal) {
// Axios: signal is always separate
// Angular with mutator: signal is separate (mutator pattern)
// Angular without mutator: signal is wrapped (native pattern)
// Fetch/other: signal is wrapped
if (httpClient === OutputHttpClient.AXIOS) {
return signalVar;
}
if (httpClient === OutputHttpClient.ANGULAR && mutator) {
return signalVar;
}
return `{ ${signalProp} }`;
}
return '';
};
export const getHookOptions = ({
isRequestOptions,
httpClient,
mutator,
useRuntimeFetcher = false,
}: {
isRequestOptions: boolean;
httpClient: OutputHttpClient;
mutator?: GeneratorMutator;
useRuntimeFetcher?: boolean;
}) => {
if (!isRequestOptions) {
return '';
}
let value = 'const {query: queryOptions';
if (!mutator) {
if (httpClient === OutputHttpClient.AXIOS) {
value += ', axios: axiosOptions';
} else if (httpClient === OutputHttpClient.FETCH && useRuntimeFetcher) {
value += ', fetch: fetchOptions, fetcher: fetcherFn';
} else {
value += ', fetch: fetchOptions';
}
}
if (mutator?.hasSecondArg) {
value += ', request: requestOptions';
}
value += '} = options ?? {};';
return value;
};
// Helper to deduplicate union type string: "A | B | B" -> "A | B"
const dedupeUnionTypes = (types: string): string => {
if (!types) return types;
// Split by '|', trim spaces, filter out empty, and dedupe using a Set
const unique = [
...new Set(
types
.split('|')
.map((t) => t.trim())
.filter(Boolean),
),
];
return unique.join(' | ');
};
export const getQueryErrorType = (
operationName: string,
response: GetterResponse,
httpClient: OutputHttpClient,
mutator?: GeneratorMutator,
) => {
const errorsType = dedupeUnionTypes(response.definition.errors || 'unknown');
if (mutator) {
return mutator.hasErrorType
? `${mutator.default ? pascal(operationName) : ''}ErrorType<${errorsType}>`
: errorsType;
} else {
return httpClient === OutputHttpClient.AXIOS
? `AxiosError<${errorsType}>`
: errorsType;
}
};
export const getHooksOptionImplementation = (
isRequestOptions: boolean,
httpClient: OutputHttpClient,
operationName: string,
mutator?: GeneratorMutator,
useRuntimeFetcher?: boolean,
) => {
const fetcherOption =
httpClient === OutputHttpClient.FETCH && useRuntimeFetcher
? ', fetcher: fetcherFn'
: '';
const options =
httpClient === OutputHttpClient.AXIOS
? ', axios: axiosOptions'
: `, fetch: fetchOptions${fetcherOption}`;
return isRequestOptions
? `const mutationKey = ['${operationName}'];
const {mutation: mutationOptions${
mutator
? mutator.hasSecondArg
? ', request: requestOptions'
: ''
: options
}} = options ?
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
options
: {...options, mutation: {...options.mutation, mutationKey}}
: {mutation: { mutationKey, }${mutator?.hasSecondArg ? ', request: undefined' : ''}${mutator ? '' : httpClient === OutputHttpClient.AXIOS ? ', axios: undefined' : ', fetch: undefined'}};`
: '';
};
export const getMutationRequestArgs = (
isRequestOptions: boolean,
httpClient: OutputHttpClient,
mutator?: GeneratorMutator,
useRuntimeFetcher?: boolean,
) => {
const options =
httpClient === OutputHttpClient.AXIOS ? 'axiosOptions' : 'fetchOptions';
const fetcherArg =
httpClient === OutputHttpClient.FETCH && useRuntimeFetcher
? ', fetcherFn'
: '';
// For Angular mutators with hasSecondArg, pass http (which is injected in inject* fn)
// http is required as first param so no assertion needed
if (mutator?.hasSecondArg && httpClient === OutputHttpClient.ANGULAR) {
return 'http';
}
return isRequestOptions
? mutator
? mutator.hasSecondArg
? 'requestOptions'
: ''
: `${options}${fetcherArg}`
: '';
};
export const getHttpFunctionQueryProps = (
isVue: boolean,
httpClient: OutputHttpClient,
queryProperties: string,
isAngular = false,
hasMutator = false,
) => {
const result =
isVue && httpClient === OutputHttpClient.FETCH && queryProperties
? queryProperties
.split(',')
.map((prop) => `unref(${prop})`)
.join(',')
: queryProperties;
// For Angular, prefix with http since request functions take HttpClient as first param
// Skip when custom mutator is used - mutator handles HTTP client internally
// http is required as first param so no assertion needed
if ((isAngular || httpClient === OutputHttpClient.ANGULAR) && !hasMutator) {
return result ? `http, ${result}` : 'http';
}
return result;
};
export const getQueryHeader: ClientHeaderBuilder = (params) => {
if (params.output.httpClient === OutputHttpClient.FETCH) {
return generateFetchHeader(params);
}
if (params.output.httpClient === OutputHttpClient.ANGULAR) {
const relevantVerbs = params.tag
? Object.values(params.verbOptions).filter(
(verbOption) => kebab(verbOption.tags[0] ?? 'default') === params.tag,
)
: Object.values(params.verbOptions);
const hasQueryParams = relevantVerbs.some((v) => v.queryParams);
return hasQueryParams ? getAngularFilteredParamsHelperBody() : '';
}
return '';
};