diff --git a/.changeset/warm-rabbits-dance.md b/.changeset/warm-rabbits-dance.md new file mode 100644 index 0000000000..722e7b8134 --- /dev/null +++ b/.changeset/warm-rabbits-dance.md @@ -0,0 +1,5 @@ +--- +"@hey-api/openapi-ts": minor +--- + +**tanstack-query**: expose `skipToken` support and `queryOptions` override on generated TanStack Query hooks diff --git a/packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/@tanstack/angular-query-experimental.gen.ts b/packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/@tanstack/angular-query-experimental.gen.ts index a168141ebe..f287ac9a07 100644 --- a/packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/@tanstack/angular-query-experimental.gen.ts +++ b/packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/@tanstack/angular-query-experimental.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions } from '@tanstack/angular-query-experimental'; +import { type DefaultError, queryOptions, skipToken } from '@tanstack/angular-query-experimental'; import { client } from '../client.gen'; import { getBar, getFoo, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooOptions = (options?: Options) => queryOptions) => queryOptions) => createQueryKey('getBar', options); -export const getBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getBar({ ...options, ...queryKey[0], @@ -70,8 +74,8 @@ export const getBarOptions = (options?: Options) => queryOptions(id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooOptions = (options?: Options) => queryOptions) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useGetFooQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooOptions, options); + export const getBarQueryKey = (options?: Options) => createQueryKey('getBar', options); -export const getBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getBar({ ...options, ...queryKey[0], @@ -70,11 +86,15 @@ export const getBarOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getBarOptions, options); diff --git a/packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/@tanstack/react-query.gen.ts index 5a6a250348..58ab80ecca 100644 --- a/packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/@tanstack/react-query.gen.ts +++ b/packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/@tanstack/react-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions } from '@tanstack/react-query'; +import { type DefaultError, queryOptions, skipToken, useQuery } from '@tanstack/react-query'; import { client } from '../client.gen'; import { getBar, getFoo, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooOptions = (options?: Options) => queryOptions) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useGetFooQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooOptions, options); + export const getBarQueryKey = (options?: Options) => createQueryKey('getBar', options); -export const getBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getBar({ ...options, ...queryKey[0], @@ -70,11 +86,15 @@ export const getBarOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getBarOptions, options); diff --git a/packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/@tanstack/solid-query.gen.ts b/packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/@tanstack/solid-query.gen.ts index 8b6d32356b..88949c0c1a 100644 --- a/packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/@tanstack/solid-query.gen.ts +++ b/packages/openapi-ts-tests/__snapshots__/plugins/@tanstack/meta/@tanstack/solid-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions } from '@tanstack/solid-query'; +import { type DefaultError, queryOptions, skipToken } from '@tanstack/solid-query'; import { client } from '../client.gen'; import { getBar, getFoo, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooOptions = (options?: Options) => queryOptions) => queryOptions) => createQueryKey('getBar', options); -export const getBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getBar({ ...options, ...queryKey[0], @@ -70,8 +74,8 @@ export const getBarOptions = (options?: Options) => queryOptions(id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooOptions = (options?: Options) => queryOptions) => queryOptions) => createQueryKey('getBar', options); -export const getBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getBar({ ...options, ...queryKey[0], @@ -70,8 +74,8 @@ export const getBarOptions = (options?: Options) => queryOptions(id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooOptions = (options?: Options) => queryOptions) => queryOptions) => createQueryKey('getBar', options); -export const getBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getBar({ ...options, ...queryKey[0], @@ -70,8 +74,8 @@ export const getBarOptions = (options?: Options) => queryOptions(id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooOptions = (options?: Options) => queryOptions>): MutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutMutation = (options?: Partial>): Mutation export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarOptions = (options?: Options) => queryOptio throwOnError: true }); return data; - }, - queryKey: getFooBarQueryKey(options) + }), + queryKey: getFooBarQueryKey(resolveOptions(options)) }); export const fooBarPostMutation = (options?: Partial>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/axios/@tanstack/angular-query-experimental.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/axios/@tanstack/angular-query-experimental.gen.ts index cef8fd3635..4ab8512e50 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/axios/@tanstack/angular-query-experimental.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/axios/@tanstack/angular-query-experimental.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/angular-query-experimental'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; @@ -40,10 +40,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); -export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const serviceWithEmptyTagOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], @@ -51,8 +55,8 @@ export const serviceWithEmptyTagOptions = (options?: Options>): MutationOptions, Options> => { @@ -99,8 +103,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -108,8 +112,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): MutationOptions, Options> => { @@ -198,8 +202,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -207,8 +211,8 @@ export const callWithDefaultParametersOptions = (options: Options>): MutationOptions, Options> => { @@ -255,8 +259,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -264,8 +268,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions, Options> => { @@ -298,8 +302,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -307,14 +311,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -322,14 +326,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -337,14 +341,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -352,14 +356,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -367,8 +371,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions, Options> => { @@ -401,8 +405,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -410,14 +414,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions, TypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -425,14 +429,14 @@ export const typesOptions = (options: Options) => queryOptions) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions, ComplexTypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -440,8 +444,8 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions, Options> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/fetch/@tanstack/angular-query-experimental.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/fetch/@tanstack/angular-query-experimental.gen.ts index 5087360ef7..db0ec3c7fd 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/fetch/@tanstack/angular-query-experimental.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/fetch/@tanstack/angular-query-experimental.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/angular-query-experimental'; import { client } from '../client.gen'; import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); -export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const serviceWithEmptyTagOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const serviceWithEmptyTagOptions = (options?: Options>): MutationOptions> => { @@ -98,8 +102,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -107,8 +111,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): MutationOptions> => { @@ -197,8 +201,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -206,8 +210,8 @@ export const callWithDefaultParametersOptions = (options: Options>): MutationOptions> => { @@ -254,8 +258,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -263,8 +267,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions> => { @@ -297,8 +301,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -306,14 +310,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -321,14 +325,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -336,14 +340,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -351,14 +355,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -366,8 +370,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions> => { @@ -400,8 +404,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -409,14 +413,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -424,14 +428,14 @@ export const typesOptions = (options: Options) => queryOptions) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -439,8 +443,8 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/name-builder/@tanstack/angular-query-experimental.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/name-builder/@tanstack/angular-query-experimental.gen.ts index b144ed7a2c..14938efa33 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/name-builder/@tanstack/angular-query-experimental.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/angular-query-experimental/name-builder/@tanstack/angular-query-experimental.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/angular-query-experimental'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooD = (options?: Options) => createQueryKey('getFoo', options); -export const getFooE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooE = (options?: Options) => queryOptions>): MutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutC = (options?: Partial>): MutationOptions export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarE = (options?: Options) => queryOptions>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/asClass/@tanstack/preact-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/asClass/@tanstack/preact-query.gen.ts index 92fa2c6b00..6e3235ff7f 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/asClass/@tanstack/preact-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/asClass/@tanstack/preact-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/preact-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const getFooOptions = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useGetFooQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooOptions, options); + export const fooPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -84,8 +100,8 @@ export const fooPutMutation = (options?: Partial>): UseMutat export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], @@ -93,10 +109,14 @@ export const getFooBarOptions = (options?: Options) => queryOptio throwOnError: true }); return data; - }, - queryKey: getFooBarQueryKey(options) + }), + queryKey: getFooBarQueryKey(resolveOptions(options)) }); +export const useGetFooBarQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooBarOptions, options); + export const fooBarPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/axios/@tanstack/preact-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/axios/@tanstack/preact-query.gen.ts index 3bf40b1ad0..2628fbf83c 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/axios/@tanstack/preact-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/axios/@tanstack/preact-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/preact-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; @@ -40,10 +40,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); -export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const serviceWithEmptyTagOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], @@ -51,10 +55,22 @@ export const serviceWithEmptyTagOptions = (options?: Options) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useServiceWithEmptyTagQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(serviceWithEmptyTagOptions, options); + export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -99,8 +115,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -108,10 +124,14 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithoutParametersAndResponseOptions, options); + export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -198,8 +218,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -207,10 +227,14 @@ export const callWithDefaultParametersOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithDefaultParametersOptions, options); + export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -255,8 +279,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -264,10 +288,14 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); +export const useDuplicateName2Query = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(duplicateName2Options, options); + export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -298,8 +326,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -307,14 +335,18 @@ export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithNoContentResponseOptions, options); + export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -322,14 +354,18 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseAndNoContentResponseOptions, options); + export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -337,14 +373,18 @@ export const dummyAOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyAOptions, options); + export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -352,14 +392,18 @@ export const dummyBOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyBOptions, options); + export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -367,10 +411,14 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); +export const useCallWithResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseOptions, options); + export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -401,8 +449,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -410,14 +458,18 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); +export const useCollectionFormatQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(collectionFormatOptions, options); + export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions, TypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -425,14 +477,18 @@ export const typesOptions = (options: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(typesOptions, options); + export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions, ComplexTypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -440,10 +496,14 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); +export const useComplexTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(complexTypesOptions, options); + export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/fetch/@tanstack/preact-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/fetch/@tanstack/preact-query.gen.ts index c3a6821f4c..1036b840bc 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/fetch/@tanstack/preact-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/fetch/@tanstack/preact-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/preact-query'; import { client } from '../client.gen'; import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); -export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const serviceWithEmptyTagOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const serviceWithEmptyTagOptions = (options?: Options) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useServiceWithEmptyTagQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(serviceWithEmptyTagOptions, options); + export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -98,8 +114,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -107,10 +123,14 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithoutParametersAndResponseOptions, options); + export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -197,8 +217,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -206,10 +226,14 @@ export const callWithDefaultParametersOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithDefaultParametersOptions, options); + export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -254,8 +278,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -263,10 +287,14 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); +export const useDuplicateName2Query = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(duplicateName2Options, options); + export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -297,8 +325,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -306,14 +334,18 @@ export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithNoContentResponseOptions, options); + export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -321,14 +353,18 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseAndNoContentResponseOptions, options); + export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -336,14 +372,18 @@ export const dummyAOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyAOptions, options); + export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -351,14 +391,18 @@ export const dummyBOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyBOptions, options); + export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -366,10 +410,14 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); +export const useCallWithResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseOptions, options); + export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -400,8 +448,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -409,14 +457,18 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); +export const useCollectionFormatQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(collectionFormatOptions, options); + export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -424,14 +476,18 @@ export const typesOptions = (options: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(typesOptions, options); + export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -439,10 +495,14 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); +export const useComplexTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(complexTypesOptions, options); + export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/name-builder/@tanstack/preact-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/name-builder/@tanstack/preact-query.gen.ts index 5552d69766..a363fc4b56 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/name-builder/@tanstack/preact-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/preact-query/name-builder/@tanstack/preact-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/preact-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooD = (options?: Options) => createQueryKey('getFoo', options); -export const getFooE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const getFooE = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useGetFooQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooE, options); + export const fooPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -84,8 +100,8 @@ export const fooPutC = (options?: Partial>): UseMutationOpti export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], @@ -93,10 +109,14 @@ export const getFooBarE = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooBarE, options); + export const fooBarPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/asClass/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/asClass/@tanstack/react-query.gen.ts index 486657ead7..acd235e3f0 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/asClass/@tanstack/react-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/asClass/@tanstack/react-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/react-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const getFooOptions = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useGetFooQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooOptions, options); + export const fooPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -84,8 +100,8 @@ export const fooPutMutation = (options?: Partial>): UseMutat export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], @@ -93,10 +109,14 @@ export const getFooBarOptions = (options?: Options) => queryOptio throwOnError: true }); return data; - }, - queryKey: getFooBarQueryKey(options) + }), + queryKey: getFooBarQueryKey(resolveOptions(options)) }); +export const useGetFooBarQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooBarOptions, options); + export const fooBarPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/axios/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/axios/@tanstack/react-query.gen.ts index da398d1700..fb2bfb2598 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/axios/@tanstack/react-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/axios/@tanstack/react-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/react-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; @@ -40,10 +40,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); -export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const serviceWithEmptyTagOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], @@ -51,10 +55,22 @@ export const serviceWithEmptyTagOptions = (options?: Options) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useServiceWithEmptyTagQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(serviceWithEmptyTagOptions, options); + export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -99,8 +115,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -108,10 +124,14 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithoutParametersAndResponseOptions, options); + export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -198,8 +218,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -207,10 +227,14 @@ export const callWithDefaultParametersOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithDefaultParametersOptions, options); + export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -255,8 +279,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -264,10 +288,14 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); +export const useDuplicateName2Query = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(duplicateName2Options, options); + export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -298,8 +326,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -307,14 +335,18 @@ export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithNoContentResponseOptions, options); + export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -322,14 +354,18 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseAndNoContentResponseOptions, options); + export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -337,14 +373,18 @@ export const dummyAOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyAOptions, options); + export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -352,14 +392,18 @@ export const dummyBOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyBOptions, options); + export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -367,10 +411,14 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); +export const useCallWithResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseOptions, options); + export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -401,8 +449,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -410,14 +458,18 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); +export const useCollectionFormatQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(collectionFormatOptions, options); + export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions, TypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -425,14 +477,18 @@ export const typesOptions = (options: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(typesOptions, options); + export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions, ComplexTypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -440,10 +496,14 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); +export const useComplexTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(complexTypesOptions, options); + export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/fetch/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/fetch/@tanstack/react-query.gen.ts index ef023fe2c6..f55e32ef87 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/fetch/@tanstack/react-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/fetch/@tanstack/react-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/react-query'; import { client } from '../client.gen'; import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); -export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const serviceWithEmptyTagOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const serviceWithEmptyTagOptions = (options?: Options) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useServiceWithEmptyTagQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(serviceWithEmptyTagOptions, options); + export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -98,8 +114,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -107,10 +123,14 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithoutParametersAndResponseOptions, options); + export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -197,8 +217,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -206,10 +226,14 @@ export const callWithDefaultParametersOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithDefaultParametersOptions, options); + export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -254,8 +278,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -263,10 +287,14 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); +export const useDuplicateName2Query = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(duplicateName2Options, options); + export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -297,8 +325,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -306,14 +334,18 @@ export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithNoContentResponseOptions, options); + export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -321,14 +353,18 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseAndNoContentResponseOptions, options); + export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -336,14 +372,18 @@ export const dummyAOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyAOptions, options); + export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -351,14 +391,18 @@ export const dummyBOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyBOptions, options); + export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -366,10 +410,14 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); +export const useCallWithResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseOptions, options); + export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -400,8 +448,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -409,14 +457,18 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); +export const useCollectionFormatQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(collectionFormatOptions, options); + export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -424,14 +476,18 @@ export const typesOptions = (options: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(typesOptions, options); + export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -439,10 +495,14 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); +export const useComplexTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(complexTypesOptions, options); + export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/name-builder/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/name-builder/@tanstack/react-query.gen.ts index 43c90277c2..34df178948 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/name-builder/@tanstack/react-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/name-builder/@tanstack/react-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/react-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooD = (options?: Options) => createQueryKey('getFoo', options); -export const getFooE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const getFooE = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useGetFooQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooE, options); + export const fooPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -84,8 +100,8 @@ export const fooPutC = (options?: Partial>): UseMutationOpti export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], @@ -93,10 +109,14 @@ export const getFooBarE = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooBarE, options); + export const fooBarPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/@tanstack/react-query.gen.ts new file mode 100644 index 0000000000..f07d7c3cd9 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/@tanstack/react-query.gen.ts @@ -0,0 +1,565 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/react-query'; + +import { client } from '../client.gen'; +import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; +import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyBData, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, GetCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TypesData, TypesResponse } from '../types.gen'; + +export type QueryKey = [ + Pick & { + _id: string; + _infinite?: boolean; + tags?: ReadonlyArray; + } +]; + +const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ + QueryKey[0] +] => { + const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; + if (infinite) { + params._infinite = infinite; + } + if (tags) { + params.tags = tags; + } + if (options?.body) { + params.body = options.body; + } + if (options?.headers) { + params.headers = options.headers; + } + if (options?.path) { + params.path = options.path; + } + if (options?.query) { + params.query = options.query; + } + return [params]; +}; + +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + +export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); + +export const serviceWithEmptyTagOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await serviceWithEmptyTag({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: serviceWithEmptyTagQueryKey(resolveOptions(options)) +}); + +const queryWithOptions = (optionsFn: Function, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useServiceWithEmptyTagQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(serviceWithEmptyTagOptions, options); + +export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await patchApiVbyApiVersionNoTag({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const fooWowMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await fooWow({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deleteCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); + +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await getCallWithoutParametersAndResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: getCallWithoutParametersAndResponseQueryKey(resolveOptions(options)) +}); + +export const useGetCallWithoutParametersAndResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithoutParametersAndResponseOptions, options); + +export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await patchCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await putCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDescriptions({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithParametersMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithParameters({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithWeirdParameterNames({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithDefaultParametersQueryKey = (options: Options) => createQueryKey('callWithDefaultParameters', options); + +export const callWithDefaultParametersOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithDefaultParameters({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithDefaultParametersQueryKey(resolveOptions(options)) +}); + +export const useCallWithDefaultParametersQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithDefaultParametersOptions, options); + +export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDefaultOptionalParameters({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callToTestOrderOfParams({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateNameMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); + +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await duplicateName2({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) +}); + +export const useDuplicateName2Query = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(duplicateName2Options, options); + +export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName3({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName4({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); + +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithNoContentResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithNoContentResponseQueryKey(resolveOptions(options)) +}); + +export const useCallWithNoContentResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithNoContentResponseOptions, options); + +export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); + +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithResponseAndNoContentResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithResponseAndNoContentResponseQueryKey(resolveOptions(options)) +}); + +export const useCallWithResponseAndNoContentResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseAndNoContentResponseOptions, options); + +export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); + +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await dummyA({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: dummyAQueryKey(resolveOptions(options)) +}); + +export const useDummyAQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyAOptions, options); + +export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); + +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await dummyB({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: dummyBQueryKey(resolveOptions(options)) +}); + +export const useDummyBQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyBOptions, options); + +export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); + +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) +}); + +export const useCallWithResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseOptions, options); + +export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDuplicateResponses({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithResponses({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); + +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await collectionFormat({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) +}); + +export const useCollectionFormatQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(collectionFormatOptions, options); + +export const typesQueryKey = (options: Options) => createQueryKey('types', options); + +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await types({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: typesQueryKey(resolveOptions(options)) +}); + +export const useTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(typesOptions, options); + +export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); + +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await complexTypes({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) +}); + +export const useComplexTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(complexTypesOptions, options); + +export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithResultFromHeader({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await testErrorCode({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * Body should not be unknown + * + * Body should not be unknown + */ +export const postApiVbyApiVersionBodyMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postApiVbyApiVersionBody({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/client.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/client.gen.ts new file mode 100644 index 0000000000..25cd14eafb --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/client.gen.ts @@ -0,0 +1,16 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type ClientOptions, type Config, createClient, createConfig } from './client'; +import type { ClientOptions as ClientOptions2 } from './types.gen'; + +/** + * The `createClientConfig()` function will be called on client initialization + * and the returned object will become the client's initial configuration. + * + * You may want to initialize your client this way instead of calling + * `setConfig()`. This is useful for example if you're using Next.js + * to ensure your client always has the correct values. + */ +export type CreateClientConfig = (override?: Config) => Config & T>; + +export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/client/client.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/client/client.gen.ts new file mode 100644 index 0000000000..14dc0a0ec5 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/client/client.gen.ts @@ -0,0 +1,290 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { createSseClient } from '../core/serverSentEvents.gen'; +import type { HttpMethod } from '../core/types.gen'; +import { getValidRequestBody } from '../core/utils.gen'; +import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; +import { + buildUrl, + createConfig, + createInterceptors, + getParseAs, + mergeConfigs, + mergeHeaders, + setAuthParams, +} from './utils.gen'; + +type ReqInit = Omit & { + body?: any; + headers: ReturnType; +}; + +export const createClient = (config: Config = {}): Client => { + let _config = mergeConfigs(createConfig(), config); + + const getConfig = (): Config => ({ ..._config }); + + const setConfig = (config: Config): Config => { + _config = mergeConfigs(_config, config); + return getConfig(); + }; + + const interceptors = createInterceptors(); + + const beforeRequest = async (options: RequestOptions) => { + const opts = { + ..._config, + ...options, + fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, + headers: mergeHeaders(_config.headers, options.headers), + serializedBody: undefined as string | undefined, + }; + + if (opts.security) { + await setAuthParams({ + ...opts, + security: opts.security, + }); + } + + if (opts.requestValidator) { + await opts.requestValidator(opts); + } + + if (opts.body !== undefined && opts.bodySerializer) { + opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; + } + + // remove Content-Type header if body is empty to avoid sending invalid requests + if (opts.body === undefined || opts.serializedBody === '') { + opts.headers.delete('Content-Type'); + } + + const url = buildUrl(opts); + + return { opts, url }; + }; + + const request: Client['request'] = async (options) => { + // @ts-expect-error + const { opts, url } = await beforeRequest(options); + const requestInit: ReqInit = { + redirect: 'follow', + ...opts, + body: getValidRequestBody(opts), + }; + + let request = new Request(url, requestInit); + + for (const fn of interceptors.request.fns) { + if (fn) { + request = await fn(request, opts); + } + } + + // fetch must be assigned here, otherwise it would throw the error: + // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation + const _fetch = opts.fetch!; + let response: Response; + + try { + response = await _fetch(request); + } catch (error) { + // Handle fetch exceptions (AbortError, network errors, etc.) + let finalError = error; + + for (const fn of interceptors.error.fns) { + if (fn) { + finalError = (await fn(error, undefined as any, request, opts)) as unknown; + } + } + + finalError = finalError || ({} as unknown); + + if (opts.throwOnError) { + throw finalError; + } + + // Return error response + return opts.responseStyle === 'data' + ? undefined + : { + error: finalError, + request, + response: undefined as any, + }; + } + + for (const fn of interceptors.response.fns) { + if (fn) { + response = await fn(response, request, opts); + } + } + + const result = { + request, + response, + }; + + if (response.ok) { + const parseAs = + (opts.parseAs === 'auto' + ? getParseAs(response.headers.get('Content-Type')) + : opts.parseAs) ?? 'json'; + + if (response.status === 204 || response.headers.get('Content-Length') === '0') { + let emptyData: any; + switch (parseAs) { + case 'arrayBuffer': + case 'blob': + case 'text': + emptyData = await response[parseAs](); + break; + case 'formData': + emptyData = new FormData(); + break; + case 'stream': + emptyData = response.body; + break; + case 'json': + default: + emptyData = {}; + break; + } + return opts.responseStyle === 'data' + ? emptyData + : { + data: emptyData, + ...result, + }; + } + + let data: any; + switch (parseAs) { + case 'arrayBuffer': + case 'blob': + case 'formData': + case 'text': + data = await response[parseAs](); + break; + case 'json': { + // Some servers return 200 with no Content-Length and empty body. + // response.json() would throw; read as text and parse if non-empty. + const text = await response.text(); + data = text ? JSON.parse(text) : {}; + break; + } + case 'stream': + return opts.responseStyle === 'data' + ? response.body + : { + data: response.body, + ...result, + }; + } + + if (parseAs === 'json') { + if (opts.responseValidator) { + await opts.responseValidator(data); + } + + if (opts.responseTransformer) { + data = await opts.responseTransformer(data); + } + } + + return opts.responseStyle === 'data' + ? data + : { + data, + ...result, + }; + } + + const textError = await response.text(); + let jsonError: unknown; + + try { + jsonError = JSON.parse(textError); + } catch { + // noop + } + + const error = jsonError ?? textError; + let finalError = error; + + for (const fn of interceptors.error.fns) { + if (fn) { + finalError = (await fn(error, response, request, opts)) as string; + } + } + + finalError = finalError || ({} as string); + + if (opts.throwOnError) { + throw finalError; + } + + // TODO: we probably want to return error and improve types + return opts.responseStyle === 'data' + ? undefined + : { + error: finalError, + ...result, + }; + }; + + const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => + request({ ...options, method }); + + const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { + const { opts, url } = await beforeRequest(options); + return createSseClient({ + ...opts, + body: opts.body as BodyInit | null | undefined, + headers: opts.headers as unknown as Record, + method, + onRequest: async (url, init) => { + let request = new Request(url, init); + for (const fn of interceptors.request.fns) { + if (fn) { + request = await fn(request, opts); + } + } + return request; + }, + serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, + url, + }); + }; + + const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); + + return { + buildUrl: _buildUrl, + connect: makeMethodFn('CONNECT'), + delete: makeMethodFn('DELETE'), + get: makeMethodFn('GET'), + getConfig, + head: makeMethodFn('HEAD'), + interceptors, + options: makeMethodFn('OPTIONS'), + patch: makeMethodFn('PATCH'), + post: makeMethodFn('POST'), + put: makeMethodFn('PUT'), + request, + setConfig, + sse: { + connect: makeSseFn('CONNECT'), + delete: makeSseFn('DELETE'), + get: makeSseFn('GET'), + head: makeSseFn('HEAD'), + options: makeSseFn('OPTIONS'), + patch: makeSseFn('PATCH'), + post: makeSseFn('POST'), + put: makeSseFn('PUT'), + trace: makeSseFn('TRACE'), + }, + trace: makeMethodFn('TRACE'), + } as Client; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/client/index.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/client/index.ts new file mode 100644 index 0000000000..b295edeca0 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/client/index.ts @@ -0,0 +1,25 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type { Auth } from '../core/auth.gen'; +export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; +export { + formDataBodySerializer, + jsonBodySerializer, + urlSearchParamsBodySerializer, +} from '../core/bodySerializer.gen'; +export { buildClientParams } from '../core/params.gen'; +export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; +export { createClient } from './client.gen'; +export type { + Client, + ClientOptions, + Config, + CreateClientConfig, + Options, + RequestOptions, + RequestResult, + ResolvedRequestOptions, + ResponseStyle, + TDataShape, +} from './types.gen'; +export { createConfig, mergeHeaders } from './utils.gen'; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/client/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/client/types.gen.ts new file mode 100644 index 0000000000..a3f8616511 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/client/types.gen.ts @@ -0,0 +1,214 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Auth } from '../core/auth.gen'; +import type { + ServerSentEventsOptions, + ServerSentEventsResult, +} from '../core/serverSentEvents.gen'; +import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; +import type { Middleware } from './utils.gen'; + +export type ResponseStyle = 'data' | 'fields'; + +export interface Config + extends Omit, CoreConfig { + /** + * Base URL for all requests made by this client. + */ + baseUrl?: T['baseUrl']; + /** + * Fetch API implementation. You can use this option to provide a custom + * fetch instance. + * + * @default globalThis.fetch + */ + fetch?: typeof fetch; + /** + * Please don't use the Fetch client for Next.js applications. The `next` + * options won't have any effect. + * + * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. + */ + next?: never; + /** + * Return the response data parsed in a specified format. By default, `auto` + * will infer the appropriate method from the `Content-Type` response header. + * You can override this behavior with any of the {@link Body} methods. + * Select `stream` if you don't want to parse response data at all. + * + * @default 'auto' + */ + parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; + /** + * Should we return only data or multiple fields (data, error, response, etc.)? + * + * @default 'fields' + */ + responseStyle?: ResponseStyle; + /** + * Throw an error instead of returning it in the response? + * + * @default false + */ + throwOnError?: T['throwOnError']; +} + +export interface RequestOptions< + TData = unknown, + TResponseStyle extends ResponseStyle = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, +> + extends + Config<{ + responseStyle: TResponseStyle; + throwOnError: ThrowOnError; + }>, + Pick< + ServerSentEventsOptions, + | 'onRequest' + | 'onSseError' + | 'onSseEvent' + | 'sseDefaultRetryDelay' + | 'sseMaxRetryAttempts' + | 'sseMaxRetryDelay' + > { + /** + * Any body that you want to add to your request. + * + * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} + */ + body?: unknown; + path?: Record; + query?: Record; + /** + * Security mechanism(s) to use for the request. + */ + security?: ReadonlyArray; + url: Url; +} + +export interface ResolvedRequestOptions< + TResponseStyle extends ResponseStyle = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, +> extends RequestOptions { + serializedBody?: string; +} + +export type RequestResult< + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = boolean, + TResponseStyle extends ResponseStyle = 'fields', +> = ThrowOnError extends true + ? Promise< + TResponseStyle extends 'data' + ? TData extends Record + ? TData[keyof TData] + : TData + : { + data: TData extends Record ? TData[keyof TData] : TData; + request: Request; + response: Response; + } + > + : Promise< + TResponseStyle extends 'data' + ? (TData extends Record ? TData[keyof TData] : TData) | undefined + : ( + | { + data: TData extends Record ? TData[keyof TData] : TData; + error: undefined; + } + | { + data: undefined; + error: TError extends Record ? TError[keyof TError] : TError; + } + ) & { + request: Request; + response: Response; + } + >; + +export interface ClientOptions { + baseUrl?: string; + responseStyle?: ResponseStyle; + throwOnError?: boolean; +} + +type MethodFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'>, +) => RequestResult; + +type SseFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'>, +) => Promise>; + +type RequestFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'> & + Pick>, 'method'>, +) => RequestResult; + +type BuildUrlFn = < + TData extends { + body?: unknown; + path?: Record; + query?: Record; + url: string; + }, +>( + options: TData & Options, +) => string; + +export type Client = CoreClient & { + interceptors: Middleware; +}; + +/** + * The `createClientConfig()` function will be called on client initialization + * and the returned object will become the client's initial configuration. + * + * You may want to initialize your client this way instead of calling + * `setConfig()`. This is useful for example if you're using Next.js + * to ensure your client always has the correct values. + */ +export type CreateClientConfig = ( + override?: Config, +) => Config & T>; + +export interface TDataShape { + body?: unknown; + headers?: unknown; + path?: unknown; + query?: unknown; + url: string; +} + +type OmitKeys = Pick>; + +export type Options< + TData extends TDataShape = TDataShape, + ThrowOnError extends boolean = boolean, + TResponse = unknown, + TResponseStyle extends ResponseStyle = 'fields', +> = OmitKeys< + RequestOptions, + 'body' | 'path' | 'query' | 'url' +> & + ([TData] extends [never] ? unknown : Omit); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/client/utils.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/client/utils.gen.ts new file mode 100644 index 0000000000..b4bd2435ce --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/client/utils.gen.ts @@ -0,0 +1,316 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { getAuthToken } from '../core/auth.gen'; +import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; +import { jsonBodySerializer } from '../core/bodySerializer.gen'; +import { + serializeArrayParam, + serializeObjectParam, + serializePrimitiveParam, +} from '../core/pathSerializer.gen'; +import { getUrl } from '../core/utils.gen'; +import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; + +export const createQuerySerializer = ({ + parameters = {}, + ...args +}: QuerySerializerOptions = {}) => { + const querySerializer = (queryParams: T) => { + const search: string[] = []; + if (queryParams && typeof queryParams === 'object') { + for (const name in queryParams) { + const value = queryParams[name]; + + if (value === undefined || value === null) { + continue; + } + + const options = parameters[name] || args; + + if (Array.isArray(value)) { + const serializedArray = serializeArrayParam({ + allowReserved: options.allowReserved, + explode: true, + name, + style: 'form', + value, + ...options.array, + }); + if (serializedArray) search.push(serializedArray); + } else if (typeof value === 'object') { + const serializedObject = serializeObjectParam({ + allowReserved: options.allowReserved, + explode: true, + name, + style: 'deepObject', + value: value as Record, + ...options.object, + }); + if (serializedObject) search.push(serializedObject); + } else { + const serializedPrimitive = serializePrimitiveParam({ + allowReserved: options.allowReserved, + name, + value: value as string, + }); + if (serializedPrimitive) search.push(serializedPrimitive); + } + } + } + return search.join('&'); + }; + return querySerializer; +}; + +/** + * Infers parseAs value from provided Content-Type header. + */ +export const getParseAs = (contentType: string | null): Exclude => { + if (!contentType) { + // If no Content-Type header is provided, the best we can do is return the raw response body, + // which is effectively the same as the 'stream' option. + return 'stream'; + } + + const cleanContent = contentType.split(';')[0]?.trim(); + + if (!cleanContent) { + return; + } + + if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { + return 'json'; + } + + if (cleanContent === 'multipart/form-data') { + return 'formData'; + } + + if ( + ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) + ) { + return 'blob'; + } + + if (cleanContent.startsWith('text/')) { + return 'text'; + } + + return; +}; + +const checkForExistence = ( + options: Pick & { + headers: Headers; + }, + name?: string, +): boolean => { + if (!name) { + return false; + } + if ( + options.headers.has(name) || + options.query?.[name] || + options.headers.get('Cookie')?.includes(`${name}=`) + ) { + return true; + } + return false; +}; + +export const setAuthParams = async ({ + security, + ...options +}: Pick, 'security'> & + Pick & { + headers: Headers; + }) => { + for (const auth of security) { + if (checkForExistence(options, auth.name)) { + continue; + } + + const token = await getAuthToken(auth, options.auth); + + if (!token) { + continue; + } + + const name = auth.name ?? 'Authorization'; + + switch (auth.in) { + case 'query': + if (!options.query) { + options.query = {}; + } + options.query[name] = token; + break; + case 'cookie': + options.headers.append('Cookie', `${name}=${token}`); + break; + case 'header': + default: + options.headers.set(name, token); + break; + } + } +}; + +export const buildUrl: Client['buildUrl'] = (options) => + getUrl({ + baseUrl: options.baseUrl as string, + path: options.path, + query: options.query, + querySerializer: + typeof options.querySerializer === 'function' + ? options.querySerializer + : createQuerySerializer(options.querySerializer), + url: options.url, + }); + +export const mergeConfigs = (a: Config, b: Config): Config => { + const config = { ...a, ...b }; + if (config.baseUrl?.endsWith('/')) { + config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); + } + config.headers = mergeHeaders(a.headers, b.headers); + return config; +}; + +const headersEntries = (headers: Headers): Array<[string, string]> => { + const entries: Array<[string, string]> = []; + headers.forEach((value, key) => { + entries.push([key, value]); + }); + return entries; +}; + +export const mergeHeaders = ( + ...headers: Array['headers'] | undefined> +): Headers => { + const mergedHeaders = new Headers(); + for (const header of headers) { + if (!header) { + continue; + } + + const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); + + for (const [key, value] of iterator) { + if (value === null) { + mergedHeaders.delete(key); + } else if (Array.isArray(value)) { + for (const v of value) { + mergedHeaders.append(key, v as string); + } + } else if (value !== undefined) { + // assume object headers are meant to be JSON stringified, i.e. their + // content value in OpenAPI specification is 'application/json' + mergedHeaders.set( + key, + typeof value === 'object' ? JSON.stringify(value) : (value as string), + ); + } + } + } + return mergedHeaders; +}; + +type ErrInterceptor = ( + error: Err, + response: Res, + request: Req, + options: Options, +) => Err | Promise; + +type ReqInterceptor = (request: Req, options: Options) => Req | Promise; + +type ResInterceptor = ( + response: Res, + request: Req, + options: Options, +) => Res | Promise; + +class Interceptors { + fns: Array = []; + + clear(): void { + this.fns = []; + } + + eject(id: number | Interceptor): void { + const index = this.getInterceptorIndex(id); + if (this.fns[index]) { + this.fns[index] = null; + } + } + + exists(id: number | Interceptor): boolean { + const index = this.getInterceptorIndex(id); + return Boolean(this.fns[index]); + } + + getInterceptorIndex(id: number | Interceptor): number { + if (typeof id === 'number') { + return this.fns[id] ? id : -1; + } + return this.fns.indexOf(id); + } + + update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { + const index = this.getInterceptorIndex(id); + if (this.fns[index]) { + this.fns[index] = fn; + return id; + } + return false; + } + + use(fn: Interceptor): number { + this.fns.push(fn); + return this.fns.length - 1; + } +} + +export interface Middleware { + error: Interceptors>; + request: Interceptors>; + response: Interceptors>; +} + +export const createInterceptors = (): Middleware< + Req, + Res, + Err, + Options +> => ({ + error: new Interceptors>(), + request: new Interceptors>(), + response: new Interceptors>(), +}); + +const defaultQuerySerializer = createQuerySerializer({ + allowReserved: false, + array: { + explode: true, + style: 'form', + }, + object: { + explode: true, + style: 'deepObject', + }, +}); + +const defaultHeaders = { + 'Content-Type': 'application/json', +}; + +export const createConfig = ( + override: Config & T> = {}, +): Config & T> => ({ + ...jsonBodySerializer, + headers: defaultHeaders, + parseAs: 'auto', + querySerializer: defaultQuerySerializer, + ...override, +}); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/auth.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/auth.gen.ts new file mode 100644 index 0000000000..3ebf994788 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/auth.gen.ts @@ -0,0 +1,41 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type AuthToken = string | undefined; + +export interface Auth { + /** + * Which part of the request do we use to send the auth? + * + * @default 'header' + */ + in?: 'header' | 'query' | 'cookie'; + /** + * Header or query parameter name. + * + * @default 'Authorization' + */ + name?: string; + scheme?: 'basic' | 'bearer'; + type: 'apiKey' | 'http'; +} + +export const getAuthToken = async ( + auth: Auth, + callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, +): Promise => { + const token = typeof callback === 'function' ? await callback(auth) : callback; + + if (!token) { + return; + } + + if (auth.scheme === 'bearer') { + return `Bearer ${token}`; + } + + if (auth.scheme === 'basic') { + return `Basic ${btoa(token)}`; + } + + return token; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/bodySerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/bodySerializer.gen.ts new file mode 100644 index 0000000000..67daca60f8 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/bodySerializer.gen.ts @@ -0,0 +1,82 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; + +export type QuerySerializer = (query: Record) => string; + +export type BodySerializer = (body: unknown) => unknown; + +type QuerySerializerOptionsObject = { + allowReserved?: boolean; + array?: Partial>; + object?: Partial>; +}; + +export type QuerySerializerOptions = QuerySerializerOptionsObject & { + /** + * Per-parameter serialization overrides. When provided, these settings + * override the global array/object settings for specific parameter names. + */ + parameters?: Record; +}; + +const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { + if (typeof value === 'string' || value instanceof Blob) { + data.append(key, value); + } else if (value instanceof Date) { + data.append(key, value.toISOString()); + } else { + data.append(key, JSON.stringify(value)); + } +}; + +const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { + if (typeof value === 'string') { + data.append(key, value); + } else { + data.append(key, JSON.stringify(value)); + } +}; + +export const formDataBodySerializer = { + bodySerializer: (body: unknown): FormData => { + const data = new FormData(); + + Object.entries(body as Record).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + if (Array.isArray(value)) { + value.forEach((v) => serializeFormDataPair(data, key, v)); + } else { + serializeFormDataPair(data, key, value); + } + }); + + return data; + }, +}; + +export const jsonBodySerializer = { + bodySerializer: (body: unknown): string => + JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), +}; + +export const urlSearchParamsBodySerializer = { + bodySerializer: (body: unknown): string => { + const data = new URLSearchParams(); + + Object.entries(body as Record).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + if (Array.isArray(value)) { + value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); + } else { + serializeUrlSearchParamsPair(data, key, value); + } + }); + + return data.toString(); + }, +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/params.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/params.gen.ts new file mode 100644 index 0000000000..7955601a5c --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/params.gen.ts @@ -0,0 +1,169 @@ +// This file is auto-generated by @hey-api/openapi-ts + +type Slot = 'body' | 'headers' | 'path' | 'query'; + +export type Field = + | { + in: Exclude; + /** + * Field name. This is the name we want the user to see and use. + */ + key: string; + /** + * Field mapped name. This is the name we want to use in the request. + * If omitted, we use the same value as `key`. + */ + map?: string; + } + | { + in: Extract; + /** + * Key isn't required for bodies. + */ + key?: string; + map?: string; + } + | { + /** + * Field name. This is the name we want the user to see and use. + */ + key: string; + /** + * Field mapped name. This is the name we want to use in the request. + * If `in` is omitted, `map` aliases `key` to the transport layer. + */ + map: Slot; + }; + +export interface Fields { + allowExtra?: Partial>; + args?: ReadonlyArray; +} + +export type FieldsConfig = ReadonlyArray; + +const extraPrefixesMap: Record = { + $body_: 'body', + $headers_: 'headers', + $path_: 'path', + $query_: 'query', +}; +const extraPrefixes = Object.entries(extraPrefixesMap); + +type KeyMap = Map< + string, + | { + in: Slot; + map?: string; + } + | { + in?: never; + map: Slot; + } +>; + +const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { + if (!map) { + map = new Map(); + } + + for (const config of fields) { + if ('in' in config) { + if (config.key) { + map.set(config.key, { + in: config.in, + map: config.map, + }); + } + } else if ('key' in config) { + map.set(config.key, { + map: config.map, + }); + } else if (config.args) { + buildKeyMap(config.args, map); + } + } + + return map; +}; + +interface Params { + body: unknown; + headers: Record; + path: Record; + query: Record; +} + +const stripEmptySlots = (params: Params) => { + for (const [slot, value] of Object.entries(params)) { + if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { + delete params[slot as Slot]; + } + } +}; + +export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { + const params: Params = { + body: {}, + headers: {}, + path: {}, + query: {}, + }; + + const map = buildKeyMap(fields); + + let config: FieldsConfig[number] | undefined; + + for (const [index, arg] of args.entries()) { + if (fields[index]) { + config = fields[index]; + } + + if (!config) { + continue; + } + + if ('in' in config) { + if (config.key) { + const field = map.get(config.key)!; + const name = field.map || config.key; + if (field.in) { + (params[field.in] as Record)[name] = arg; + } + } else { + params.body = arg; + } + } else { + for (const [key, value] of Object.entries(arg ?? {})) { + const field = map.get(key); + + if (field) { + if (field.in) { + const name = field.map || key; + (params[field.in] as Record)[name] = value; + } else { + params[field.map] = value; + } + } else { + const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); + + if (extra) { + const [prefix, slot] = extra; + (params[slot] as Record)[key.slice(prefix.length)] = value; + } else if ('allowExtra' in config && config.allowExtra) { + for (const [slot, allowed] of Object.entries(config.allowExtra)) { + if (allowed) { + (params[slot as Slot] as Record)[key] = value; + break; + } + } + } + } + } + } + } + + stripEmptySlots(params); + + return params; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/pathSerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/pathSerializer.gen.ts new file mode 100644 index 0000000000..994b2848c6 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/pathSerializer.gen.ts @@ -0,0 +1,171 @@ +// This file is auto-generated by @hey-api/openapi-ts + +interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} + +interface SerializePrimitiveOptions { + allowReserved?: boolean; + name: string; +} + +export interface SerializerOptions { + /** + * @default true + */ + explode: boolean; + style: T; +} + +export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; +export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; +type MatrixStyle = 'label' | 'matrix' | 'simple'; +export type ObjectStyle = 'form' | 'deepObject'; +type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; + +interface SerializePrimitiveParam extends SerializePrimitiveOptions { + value: string; +} + +export const separatorArrayExplode = (style: ArraySeparatorStyle) => { + switch (style) { + case 'label': + return '.'; + case 'matrix': + return ';'; + case 'simple': + return ','; + default: + return '&'; + } +}; + +export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { + switch (style) { + case 'form': + return ','; + case 'pipeDelimited': + return '|'; + case 'spaceDelimited': + return '%20'; + default: + return ','; + } +}; + +export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { + switch (style) { + case 'label': + return '.'; + case 'matrix': + return ';'; + case 'simple': + return ','; + default: + return '&'; + } +}; + +export const serializeArrayParam = ({ + allowReserved, + explode, + name, + style, + value, +}: SerializeOptions & { + value: unknown[]; +}) => { + if (!explode) { + const joinedValues = ( + allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) + ).join(separatorArrayNoExplode(style)); + switch (style) { + case 'label': + return `.${joinedValues}`; + case 'matrix': + return `;${name}=${joinedValues}`; + case 'simple': + return joinedValues; + default: + return `${name}=${joinedValues}`; + } + } + + const separator = separatorArrayExplode(style); + const joinedValues = value + .map((v) => { + if (style === 'label' || style === 'simple') { + return allowReserved ? v : encodeURIComponent(v as string); + } + + return serializePrimitiveParam({ + allowReserved, + name, + value: v as string, + }); + }) + .join(separator); + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; +}; + +export const serializePrimitiveParam = ({ + allowReserved, + name, + value, +}: SerializePrimitiveParam) => { + if (value === undefined || value === null) { + return ''; + } + + if (typeof value === 'object') { + throw new Error( + 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', + ); + } + + return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; +}; + +export const serializeObjectParam = ({ + allowReserved, + explode, + name, + style, + value, + valueOnly, +}: SerializeOptions & { + value: Record | Date; + valueOnly?: boolean; +}) => { + if (value instanceof Date) { + return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; + } + + if (style !== 'deepObject' && !explode) { + let values: string[] = []; + Object.entries(value).forEach(([key, v]) => { + values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; + }); + const joinedValues = values.join(','); + switch (style) { + case 'form': + return `${name}=${joinedValues}`; + case 'label': + return `.${joinedValues}`; + case 'matrix': + return `;${name}=${joinedValues}`; + default: + return joinedValues; + } + } + + const separator = separatorObjectExplode(style); + const joinedValues = Object.entries(value) + .map(([key, v]) => + serializePrimitiveParam({ + allowReserved, + name: style === 'deepObject' ? `${name}[${key}]` : key, + value: v as string, + }), + ) + .join(separator); + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/queryKeySerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/queryKeySerializer.gen.ts new file mode 100644 index 0000000000..5000df606f --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/queryKeySerializer.gen.ts @@ -0,0 +1,117 @@ +// This file is auto-generated by @hey-api/openapi-ts + +/** + * JSON-friendly union that mirrors what Pinia Colada can hash. + */ +export type JsonValue = + | null + | string + | number + | boolean + | JsonValue[] + | { [key: string]: JsonValue }; + +/** + * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. + */ +export const queryKeyJsonReplacer = (_key: string, value: unknown) => { + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { + return undefined; + } + if (typeof value === 'bigint') { + return value.toString(); + } + if (value instanceof Date) { + return value.toISOString(); + } + return value; +}; + +/** + * Safely stringifies a value and parses it back into a JsonValue. + */ +export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { + try { + const json = JSON.stringify(input, queryKeyJsonReplacer); + if (json === undefined) { + return undefined; + } + return JSON.parse(json) as JsonValue; + } catch { + return undefined; + } +}; + +/** + * Detects plain objects (including objects with a null prototype). + */ +const isPlainObject = (value: unknown): value is Record => { + if (value === null || typeof value !== 'object') { + return false; + } + const prototype = Object.getPrototypeOf(value as object); + return prototype === Object.prototype || prototype === null; +}; + +/** + * Turns URLSearchParams into a sorted JSON object for deterministic keys. + */ +const serializeSearchParams = (params: URLSearchParams): JsonValue => { + const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); + const result: Record = {}; + + for (const [key, value] of entries) { + const existing = result[key]; + if (existing === undefined) { + result[key] = value; + continue; + } + + if (Array.isArray(existing)) { + (existing as string[]).push(value); + } else { + result[key] = [existing, value]; + } + } + + return result; +}; + +/** + * Normalizes any accepted value into a JSON-friendly shape for query keys. + */ +export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { + if (value === null) { + return null; + } + + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return value; + } + + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { + return undefined; + } + + if (typeof value === 'bigint') { + return value.toString(); + } + + if (value instanceof Date) { + return value.toISOString(); + } + + if (Array.isArray(value)) { + return stringifyToJsonValue(value); + } + + if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { + return serializeSearchParams(value); + } + + if (isPlainObject(value)) { + return stringifyToJsonValue(value); + } + + return undefined; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/serverSentEvents.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/serverSentEvents.gen.ts new file mode 100644 index 0000000000..6aa6cf02a4 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/serverSentEvents.gen.ts @@ -0,0 +1,243 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Config } from './types.gen'; + +export type ServerSentEventsOptions = Omit & + Pick & { + /** + * Fetch API implementation. You can use this option to provide a custom + * fetch instance. + * + * @default globalThis.fetch + */ + fetch?: typeof fetch; + /** + * Implementing clients can call request interceptors inside this hook. + */ + onRequest?: (url: string, init: RequestInit) => Promise; + /** + * Callback invoked when a network or parsing error occurs during streaming. + * + * This option applies only if the endpoint returns a stream of events. + * + * @param error The error that occurred. + */ + onSseError?: (error: unknown) => void; + /** + * Callback invoked when an event is streamed from the server. + * + * This option applies only if the endpoint returns a stream of events. + * + * @param event Event streamed from the server. + * @returns Nothing (void). + */ + onSseEvent?: (event: StreamEvent) => void; + serializedBody?: RequestInit['body']; + /** + * Default retry delay in milliseconds. + * + * This option applies only if the endpoint returns a stream of events. + * + * @default 3000 + */ + sseDefaultRetryDelay?: number; + /** + * Maximum number of retry attempts before giving up. + */ + sseMaxRetryAttempts?: number; + /** + * Maximum retry delay in milliseconds. + * + * Applies only when exponential backoff is used. + * + * This option applies only if the endpoint returns a stream of events. + * + * @default 30000 + */ + sseMaxRetryDelay?: number; + /** + * Optional sleep function for retry backoff. + * + * Defaults to using `setTimeout`. + */ + sseSleepFn?: (ms: number) => Promise; + url: string; + }; + +export interface StreamEvent { + data: TData; + event?: string; + id?: string; + retry?: number; +} + +export type ServerSentEventsResult = { + stream: AsyncGenerator< + TData extends Record ? TData[keyof TData] : TData, + TReturn, + TNext + >; +}; + +export const createSseClient = ({ + onRequest, + onSseError, + onSseEvent, + responseTransformer, + responseValidator, + sseDefaultRetryDelay, + sseMaxRetryAttempts, + sseMaxRetryDelay, + sseSleepFn, + url, + ...options +}: ServerSentEventsOptions): ServerSentEventsResult => { + let lastEventId: string | undefined; + + const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + + const createStream = async function* () { + let retryDelay: number = sseDefaultRetryDelay ?? 3000; + let attempt = 0; + const signal = options.signal ?? new AbortController().signal; + + while (true) { + if (signal.aborted) break; + + attempt++; + + const headers = + options.headers instanceof Headers + ? options.headers + : new Headers(options.headers as Record | undefined); + + if (lastEventId !== undefined) { + headers.set('Last-Event-ID', lastEventId); + } + + try { + const requestInit: RequestInit = { + redirect: 'follow', + ...options, + body: options.serializedBody, + headers, + signal, + }; + let request = new Request(url, requestInit); + if (onRequest) { + request = await onRequest(url, requestInit); + } + // fetch must be assigned here, otherwise it would throw the error: + // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation + const _fetch = options.fetch ?? globalThis.fetch; + const response = await _fetch(request); + + if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); + + if (!response.body) throw new Error('No body in SSE response'); + + const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); + + let buffer = ''; + + const abortHandler = () => { + try { + reader.cancel(); + } catch { + // noop + } + }; + + signal.addEventListener('abort', abortHandler); + + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + buffer += value; + // Normalize line endings: CRLF -> LF, then CR -> LF + buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); + + const chunks = buffer.split('\n\n'); + buffer = chunks.pop() ?? ''; + + for (const chunk of chunks) { + const lines = chunk.split('\n'); + const dataLines: Array = []; + let eventName: string | undefined; + + for (const line of lines) { + if (line.startsWith('data:')) { + dataLines.push(line.replace(/^data:\s*/, '')); + } else if (line.startsWith('event:')) { + eventName = line.replace(/^event:\s*/, ''); + } else if (line.startsWith('id:')) { + lastEventId = line.replace(/^id:\s*/, ''); + } else if (line.startsWith('retry:')) { + const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); + if (!Number.isNaN(parsed)) { + retryDelay = parsed; + } + } + } + + let data: unknown; + let parsedJson = false; + + if (dataLines.length) { + const rawData = dataLines.join('\n'); + try { + data = JSON.parse(rawData); + parsedJson = true; + } catch { + data = rawData; + } + } + + if (parsedJson) { + if (responseValidator) { + await responseValidator(data); + } + + if (responseTransformer) { + data = await responseTransformer(data); + } + } + + onSseEvent?.({ + data, + event: eventName, + id: lastEventId, + retry: retryDelay, + }); + + if (dataLines.length) { + yield data as any; + } + } + } + } finally { + signal.removeEventListener('abort', abortHandler); + reader.releaseLock(); + } + + break; // exit loop on normal completion + } catch (error) { + // connection failed or aborted; retry after delay + onSseError?.(error); + + if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { + break; // stop after firing error + } + + // exponential backoff: double retry each attempt, cap at 30s + const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); + await sleep(backoff); + } + } + }; + + const stream = createStream(); + + return { stream }; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/types.gen.ts new file mode 100644 index 0000000000..97463257e4 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/types.gen.ts @@ -0,0 +1,104 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Auth, AuthToken } from './auth.gen'; +import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; + +export type HttpMethod = + | 'connect' + | 'delete' + | 'get' + | 'head' + | 'options' + | 'patch' + | 'post' + | 'put' + | 'trace'; + +export type Client< + RequestFn = never, + Config = unknown, + MethodFn = never, + BuildUrlFn = never, + SseFn = never, +> = { + /** + * Returns the final request URL. + */ + buildUrl: BuildUrlFn; + getConfig: () => Config; + request: RequestFn; + setConfig: (config: Config) => Config; +} & { + [K in HttpMethod]: MethodFn; +} & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); + +export interface Config { + /** + * Auth token or a function returning auth token. The resolved value will be + * added to the request payload as defined by its `security` array. + */ + auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; + /** + * A function for serializing request body parameter. By default, + * {@link JSON.stringify()} will be used. + */ + bodySerializer?: BodySerializer | null; + /** + * An object containing any HTTP headers that you want to pre-populate your + * `Headers` object with. + * + * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} + */ + headers?: + | RequestInit['headers'] + | Record< + string, + string | number | boolean | (string | number | boolean)[] | null | undefined | unknown + >; + /** + * The request method. + * + * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} + */ + method?: Uppercase; + /** + * A function for serializing request query parameters. By default, arrays + * will be exploded in form style, objects will be exploded in deepObject + * style, and reserved characters are percent-encoded. + * + * This method will have no effect if the native `paramsSerializer()` Axios + * API function is used. + * + * {@link https://swagger.io/docs/specification/serialization/#query View examples} + */ + querySerializer?: QuerySerializer | QuerySerializerOptions; + /** + * A function validating request data. This is useful if you want to ensure + * the request conforms to the desired shape, so it can be safely sent to + * the server. + */ + requestValidator?: (data: unknown) => Promise; + /** + * A function transforming response data before it's returned. This is useful + * for post-processing data, e.g. converting ISO strings into Date objects. + */ + responseTransformer?: (data: unknown) => Promise; + /** + * A function validating response data. This is useful if you want to ensure + * the response conforms to the desired shape, so it can be safely passed to + * the transformers and returned to the user. + */ + responseValidator?: (data: unknown) => Promise; +} + +type IsExactlyNeverOrNeverUndefined = [T] extends [never] + ? true + : [T] extends [never | undefined] + ? [undefined] extends [T] + ? false + : true + : false; + +export type OmitNever> = { + [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/utils.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/utils.gen.ts new file mode 100644 index 0000000000..e7ddbe3541 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/core/utils.gen.ts @@ -0,0 +1,140 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; +import { + type ArraySeparatorStyle, + serializeArrayParam, + serializeObjectParam, + serializePrimitiveParam, +} from './pathSerializer.gen'; + +export interface PathSerializer { + path: Record; + url: string; +} + +export const PATH_PARAM_RE = /\{[^{}]+\}/g; + +export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { + let url = _url; + const matches = _url.match(PATH_PARAM_RE); + if (matches) { + for (const match of matches) { + let explode = false; + let name = match.substring(1, match.length - 1); + let style: ArraySeparatorStyle = 'simple'; + + if (name.endsWith('*')) { + explode = true; + name = name.substring(0, name.length - 1); + } + + if (name.startsWith('.')) { + name = name.substring(1); + style = 'label'; + } else if (name.startsWith(';')) { + name = name.substring(1); + style = 'matrix'; + } + + const value = path[name]; + + if (value === undefined || value === null) { + continue; + } + + if (Array.isArray(value)) { + url = url.replace(match, serializeArrayParam({ explode, name, style, value })); + continue; + } + + if (typeof value === 'object') { + url = url.replace( + match, + serializeObjectParam({ + explode, + name, + style, + value: value as Record, + valueOnly: true, + }), + ); + continue; + } + + if (style === 'matrix') { + url = url.replace( + match, + `;${serializePrimitiveParam({ + name, + value: value as string, + })}`, + ); + continue; + } + + const replaceValue = encodeURIComponent( + style === 'label' ? `.${value as string}` : (value as string), + ); + url = url.replace(match, replaceValue); + } + } + return url; +}; + +export const getUrl = ({ + baseUrl, + path, + query, + querySerializer, + url: _url, +}: { + baseUrl?: string; + path?: Record; + query?: Record; + querySerializer: QuerySerializer; + url: string; +}) => { + const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; + let url = (baseUrl ?? '') + pathUrl; + if (path) { + url = defaultPathSerializer({ path, url }); + } + let search = query ? querySerializer(query) : ''; + if (search.startsWith('?')) { + search = search.substring(1); + } + if (search) { + url += `?${search}`; + } + return url; +}; + +export function getValidRequestBody(options: { + body?: unknown; + bodySerializer?: BodySerializer | null; + serializedBody?: unknown; +}) { + const hasBody = options.body !== undefined; + const isSerializedBody = hasBody && options.bodySerializer; + + if (isSerializedBody) { + if ('serializedBody' in options) { + const hasSerializedBody = + options.serializedBody !== undefined && options.serializedBody !== ''; + + return hasSerializedBody ? options.serializedBody : null; + } + + // not all clients implement a serializedBody property (i.e. client-axios) + return options.body !== '' ? options.body : null; + } + + // plain/text body + if (hasBody) { + return options.body; + } + + // no body was provided + return undefined; +} diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/index.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/index.ts new file mode 100644 index 0000000000..ee6d0288c0 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/index.ts @@ -0,0 +1,4 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from './sdk.gen'; +export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/sdk.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/sdk.gen.ts new file mode 100644 index 0000000000..6776488ce6 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/sdk.gen.ts @@ -0,0 +1,127 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Client, Options as Options2, TDataShape } from './client'; +import { client } from './client.gen'; +import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses } from './types.gen'; + +export type Options = Options2 & { + /** + * You can provide a client instance returned by `createClient()` instead of + * individual options. This might be also useful if you want to implement a + * custom client. + */ + client?: Client; + /** + * You can pass arbitrary values through the `meta` object. This can be + * used to access values that aren't defined as part of the SDK function. + */ + meta?: Record; +}; + +export const serviceWithEmptyTag = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); + +export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); + +export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); + +export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); + +export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); + +export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); + +export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); + +export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); + +export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); + +export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); + +export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions/', ...options }); + +export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); + +export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ + querySerializer: { parameters: { parameterModel: { object: { explode: false, style: 'form' } } } }, + url: '/api/v{api-version}/defaults', + ...options +}); + +export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); + +export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); + +export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); + +export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); + +export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); + +export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); + +export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); + +export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); + +export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); + +export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); + +export const collectionFormat = (options: Options) => (options.client ?? client).get({ + querySerializer: { parameters: { + parameterArrayCSV: { array: { explode: false } }, + parameterArraySSV: { array: { explode: false } }, + parameterArrayTSV: { array: { explode: false } }, + parameterArrayPipes: { array: { explode: false } } + } }, + url: '/api/v{api-version}/collectionFormat', + ...options +}); + +export const types = (options: Options) => (options.client ?? client).get({ + querySerializer: { parameters: { parameterArray: { array: { explode: false } }, parameterDictionary: { object: { explode: false, style: 'form' } } } }, + url: '/api/v{api-version}/types', + ...options +}); + +export const complexTypes = (options: Options) => (options.client ?? client).get({ + querySerializer: { parameters: { parameterObject: { object: { explode: false, style: 'form' } }, parameterReference: { object: { explode: false, style: 'form' } } } }, + url: '/api/v{api-version}/complex', + ...options +}); + +export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); + +export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); + +export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); + +/** + * Body should not be unknown + * + * Body should not be unknown + */ +export const postApiVbyApiVersionBody = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/body', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/types.gen.ts new file mode 100644 index 0000000000..d69b074040 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/skipToken/types.gen.ts @@ -0,0 +1,1190 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type ClientOptions = { + baseUrl: 'http://localhost:3000/base' | (string & {}); +}; + +export type ExternalRefA = ExternalSharedModel; + +export type ExternalRefB = ExternalSharedModel; + +/** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ +export type CommentWithBreaks = number; + +/** + * Testing backticks in string: `backticks` and ```multiple backticks``` should work + */ +export type CommentWithBackticks = number; + +/** + * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work + */ +export type CommentWithBackticksAndQuotes = number; + +/** + * Testing slashes in string: \backwards\\\ and /forwards/// should work + */ +export type CommentWithSlashes = number; + +/** + * Testing expression placeholders in string: ${expression} should work + */ +export type CommentWithExpressionPlaceholders = number; + +/** + * Testing quotes in string: 'single quote''' and "double quotes""" should work + */ +export type CommentWithQuotes = number; + +/** + * Testing reserved characters in string: * inline * and ** inline ** should work + */ +export type CommentWithReservedCharacters = number; + +/** + * This is a simple number + */ +export type SimpleInteger = number; + +/** + * This is a simple boolean + */ +export type SimpleBoolean = boolean; + +/** + * This is a simple string + */ +export type SimpleString = string; + +/** + * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) + */ +export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; + +/** + * This is a simple file + */ +export type SimpleFile = Blob | File; + +export type SimpleReference = ModelWithString; + +/** + * This is a simple string + */ +export type SimpleStringWithPattern = string; + +/** + * This is a simple enum with strings + */ +export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; + +/** + * This is a simple enum with numbers + */ +export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; + +/** + * Success=1,Warning=2,Error=3 + */ +export type EnumFromDescription = number; + +/** + * This is a simple enum with numbers + */ +export type EnumWithExtensions = 200 | 400 | 500; + +/** + * This is a simple array with numbers + */ +export type ArrayWithNumbers = Array; + +/** + * This is a simple array with booleans + */ +export type ArrayWithBooleans = Array; + +/** + * This is a simple array with strings + */ +export type ArrayWithStrings = Array; + +/** + * This is a simple array with references + */ +export type ArrayWithReferences = Array; + +/** + * This is a simple array containing an array + */ +export type ArrayWithArray = Array>; + +/** + * This is a simple array with properties + */ +export type ArrayWithProperties = Array<{ + foo?: string; + bar?: string; +}>; + +/** + * This is a string dictionary + */ +export type DictionaryWithString = { + [key: string]: string; +}; + +/** + * This is a string reference + */ +export type DictionaryWithReference = { + [key: string]: ModelWithString; +}; + +/** + * This is a complex dictionary + */ +export type DictionaryWithArray = { + [key: string]: Array; +}; + +/** + * This is a string dictionary + */ +export type DictionaryWithDictionary = { + [key: string]: { + [key: string]: string; + }; +}; + +/** + * This is a complex dictionary + */ +export type DictionaryWithProperties = { + [key: string]: { + foo?: string; + bar?: string; + }; +}; + +/** + * This is a type-only model that defines Date as a string + */ +export type Date = string; + +/** + * This is a model with one number property + */ +export type ModelWithInteger = { + /** + * This is a simple number property + */ + prop?: number; +}; + +/** + * This is a model with one boolean property + */ +export type ModelWithBoolean = { + /** + * This is a simple boolean property + */ + prop?: boolean; +}; + +/** + * This is a model with one string property + */ +export type ModelWithString = { + /** + * This is a simple string property + */ + prop?: string; +}; + +/** + * This is a model with one string property + */ +export type ModelWithStringError = { + /** + * This is a simple string property + */ + prop?: string; +}; + +/** + * This is a model with one string property + */ +export type ModelWithNullableString = { + /** + * This is a simple string property + */ + nullableProp?: string | null; + /** + * This is a simple string property + */ + nullableRequiredProp: string | null; +}; + +/** + * This is a model with one enum + */ +export type ModelWithEnum = { + /** + * This is a simple enum with strings + */ + test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; + /** + * These are the HTTP error code enums + */ + statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; + /** + * Simple boolean enum + */ + bool?: true; +}; + +/** + * This is a model with one enum + */ +export type ModelWithEnumFromDescription = { + /** + * Success=1,Warning=2,Error=3 + */ + test?: number; +}; + +/** + * This is a model with nested enums + */ +export type ModelWithNestedEnums = { + dictionaryWithEnum?: { + [key: string]: 'Success' | 'Warning' | 'Error'; + }; + dictionaryWithEnumFromDescription?: { + [key: string]: number; + }; + arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; + arrayWithDescription?: Array; +}; + +/** + * This is a model with one property containing a reference + */ +export type ModelWithReference = { + prop?: ModelWithProperties; +}; + +/** + * This is a model with one property containing an array + */ +export type ModelWithArray = { + prop?: Array; + propWithFile?: Array; + propWithNumber?: Array; +}; + +/** + * This is a model with one property containing a dictionary + */ +export type ModelWithDictionary = { + prop?: { + [key: string]: string; + }; +}; + +/** + * This is a model with one property containing a circular reference + */ +export type ModelWithCircularReference = { + prop?: ModelWithCircularReference; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithProperties = { + required: string; + readonly requiredAndReadOnly: string; + string?: string; + number?: number; + boolean?: boolean; + reference?: ModelWithString; + 'property with space'?: string; + default?: string; + try?: string; + readonly '@namespace.string'?: string; + readonly '@namespace.integer'?: number; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithNestedProperties = { + readonly first: { + readonly second: { + readonly third: string; + }; + }; +}; + +/** + * This is a model with duplicated properties + */ +export type ModelWithDuplicateProperties = { + prop?: ModelWithString; +}; + +/** + * This is a model with ordered properties + */ +export type ModelWithOrderedProperties = { + zebra?: string; + apple?: string; + hawaii?: string; +}; + +/** + * This is a model with duplicated imports + */ +export type ModelWithDuplicateImports = { + propA?: ModelWithString; + propB?: ModelWithString; + propC?: ModelWithString; +}; + +/** + * This is a model that extends another model + */ +export type ModelThatExtends = ModelWithString & { + propExtendsA?: string; + propExtendsB?: ModelWithString; +}; + +/** + * This is a model that extends another model + */ +export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { + propExtendsC?: string; + propExtendsD?: ModelWithString; +}; + +export type Default = { + name?: string; +}; + +/** + * This is a model that contains a some patterns + */ +export type ModelWithPattern = { + key: string; + name: string; + readonly enabled?: boolean; + readonly modified?: string; + id?: string; + text?: string; + patternWithSingleQuotes?: string; + patternWithNewline?: string; + patternWithBacktick?: string; + patternWithUnicode?: string; +}; + +export type ParameterActivityParams = { + description?: string; + graduate_id?: number; + organization_id?: number; + parent_activity?: number; + post_id?: number; +}; + +export type ResponsePostActivityResponse = { + description?: string; + graduate_id?: number; + organization_id?: number; + parent_activity_id?: number; + post_id?: number; +}; + +export type FailureFailure = { + error?: string; + message?: string; + reference_code?: string; +}; + +export type ExternalSharedModel = { + id: string; + name?: string; +}; + +/** + * This is a model with one property containing a reference + */ +export type ModelWithReferenceWritable = { + prop?: ModelWithPropertiesWritable; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithPropertiesWritable = { + required: string; + string?: string; + number?: number; + boolean?: boolean; + reference?: ModelWithString; + 'property with space'?: string; + default?: string; + try?: string; +}; + +/** + * This is a model that contains a some patterns + */ +export type ModelWithPatternWritable = { + key: string; + name: string; + id?: string; + text?: string; + patternWithSingleQuotes?: string; + patternWithNewline?: string; + patternWithBacktick?: string; + patternWithUnicode?: string; +}; + +export type ServiceWithEmptyTagData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type PatchApiVbyApiVersionNoTagData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type PatchApiVbyApiVersionNoTagResponses = { + /** + * OK + */ + default: unknown; +}; + +export type FooWowData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type FooWowResponses = { + /** + * OK + */ + default: unknown; +}; + +export type DeleteCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type GetCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type HeadCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type OptionsCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PatchCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PostCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PutCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type CallWithDescriptionsData = { + body?: never; + path?: never; + query?: { + /** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ + parameterWithBreaks?: string; + /** + * Testing backticks in string: `backticks` and ```multiple backticks``` should work + */ + parameterWithBackticks?: string; + /** + * Testing slashes in string: \backwards\\\ and /forwards/// should work + */ + parameterWithSlashes?: string; + /** + * Testing expression placeholders in string: ${expression} should work + */ + parameterWithExpressionPlaceholders?: string; + /** + * Testing quotes in string: 'single quote''' and "double quotes""" should work + */ + parameterWithQuotes?: string; + /** + * Testing reserved characters in string: * inline * and ** inline ** should work + */ + parameterWithReservedCharacters?: string; + }; + url: '/api/v{api-version}/descriptions/'; +}; + +export type CallWithParametersData = { + body?: never; + headers: { + /** + * This is the parameter that goes into the header + */ + parameterHeader: string; + }; + path: { + /** + * This is the parameter that goes into the path + */ + parameterPath: string; + /** + * api-version should be required in standalone clients + */ + 'api-version': string; + }; + query: { + /** + * This is the parameter that goes into the query params + */ + parameterQuery: string; + }; + url: '/api/v{api-version}/parameters/{parameterPath}'; +}; + +export type CallWithWeirdParameterNamesData = { + /** + * This is the parameter that is sent as request body + */ + body: string; + headers: { + /** + * This is the parameter that goes into the request header + */ + 'parameter.header': string; + }; + path: { + /** + * This is the parameter that goes into the path + */ + 'parameter.path.1'?: string; + /** + * This is the parameter that goes into the path + */ + 'parameter-path-2'?: string; + /** + * This is the parameter that goes into the path + */ + 'PARAMETER-PATH-3'?: string; + /** + * api-version should be required in standalone clients + */ + 'api-version': string; + }; + query: { + /** + * This is the parameter with a reserved keyword + */ + default?: string; + /** + * This is the parameter that goes into the request query params + */ + 'parameter-query': string; + }; + url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; +}; + +export type CallWithDefaultParametersData = { + body?: never; + path?: never; + query: { + /** + * This is a simple string with default value + */ + parameterString: string; + /** + * This is a simple number with default value + */ + parameterNumber: number; + /** + * This is a simple boolean with default value + */ + parameterBoolean: boolean; + /** + * This is a simple enum with default value + */ + parameterEnum: 'Success' | 'Warning' | 'Error'; + /** + * This is a model with one string property + */ + parameterModel: { + /** + * This is a simple string property + */ + prop?: string; + }; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type CallWithDefaultOptionalParametersData = { + body?: never; + path?: never; + query?: { + /** + * This is a simple string that is optional with default value + */ + parameterString?: string; + /** + * This is a simple number that is optional with default value + */ + parameterNumber?: number; + /** + * This is a simple boolean that is optional with default value + */ + parameterBoolean?: boolean; + /** + * This is a simple enum that is optional with default value + */ + parameterEnum?: 'Success' | 'Warning' | 'Error'; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type CallToTestOrderOfParamsData = { + body?: never; + path?: never; + query: { + /** + * This is a optional string with default + */ + parameterOptionalStringWithDefault?: string; + /** + * This is a optional string with empty default + */ + parameterOptionalStringWithEmptyDefault?: string; + /** + * This is a optional string with no default + */ + parameterOptionalStringWithNoDefault?: string; + /** + * This is a string with default + */ + parameterStringWithDefault: string; + /** + * This is a string with empty default + */ + parameterStringWithEmptyDefault: string; + /** + * This is a string with no default + */ + parameterStringWithNoDefault: string; + /** + * This is a string that can be null with no default + */ + parameterStringNullableWithNoDefault?: string | null; + /** + * This is a string that can be null with default + */ + parameterStringNullableWithDefault?: string | null; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type DuplicateNameData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName2Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName3Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName4Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type CallWithNoContentResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no-content'; +}; + +export type CallWithNoContentResponseResponses = { + /** + * Success + */ + 204: unknown; +}; + +export type CallWithResponseAndNoContentResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/response-and-no-content'; +}; + +export type CallWithResponseAndNoContentResponseResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Success + */ + 204: unknown; +}; + +export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; + +export type DummyAData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/a'; +}; + +export type DummyAResponses = { + /** + * Success + */ + 204: unknown; +}; + +export type DummyBData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/b'; +}; + +export type DummyBResponses = { + /** + * Success + */ + 204: unknown; +}; + +export type CallWithResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithResponseResponses = { + /** + * Message for default response + */ + default: ModelWithString; +}; + +export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; + +export type CallWithDuplicateResponsesData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithDuplicateResponsesErrors = { + /** + * Message for 500 error + */ + 500: ModelWithStringError; + /** + * Message for 501 error + */ + 501: ModelWithStringError; + /** + * Message for 502 error + */ + 502: ModelWithStringError; + /** + * Message for default response + */ + default: ModelWithString; +}; + +export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; + +export type CallWithDuplicateResponsesResponses = { + /** + * Message for 201 response + */ + 201: ModelWithString; + /** + * Message for 202 response + */ + 202: ModelWithString; +}; + +export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; + +export type CallWithResponsesData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithResponsesErrors = { + /** + * Message for 500 error + */ + 500: ModelWithStringError; + /** + * Message for 501 error + */ + 501: ModelWithStringError; + /** + * Message for 502 error + */ + 502: ModelWithStringError; + /** + * Message for default response + */ + default: ModelWithString; +}; + +export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; + +export type CallWithResponsesResponses = { + /** + * Message for 200 response + */ + 200: { + readonly '@namespace.string'?: string; + readonly '@namespace.integer'?: number; + readonly value?: Array; + }; + /** + * Message for 201 response + */ + 201: ModelThatExtends; + /** + * Message for 202 response + */ + 202: ModelThatExtendsExtends; +}; + +export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; + +export type CollectionFormatData = { + body?: never; + path?: never; + query: { + /** + * This is an array parameter that is sent as csv format (comma-separated values) + */ + parameterArrayCSV: Array; + /** + * This is an array parameter that is sent as ssv format (space-separated values) + */ + parameterArraySSV: Array; + /** + * This is an array parameter that is sent as tsv format (tab-separated values) + */ + parameterArrayTSV: Array; + /** + * This is an array parameter that is sent as pipes format (pipe-separated values) + */ + parameterArrayPipes: Array; + /** + * This is an array parameter that is sent as multi format (multiple parameter instances) + */ + parameterArrayMulti: Array; + }; + url: '/api/v{api-version}/collectionFormat'; +}; + +export type TypesData = { + body?: never; + path?: { + /** + * This is a number parameter + */ + id?: number; + }; + query: { + /** + * This is a number parameter + */ + parameterNumber: number; + /** + * This is a string parameter + */ + parameterString: string; + /** + * This is a boolean parameter + */ + parameterBoolean: boolean; + /** + * This is an array parameter + */ + parameterArray: Array; + /** + * This is a dictionary parameter + */ + parameterDictionary: { + [key: string]: unknown; + }; + /** + * This is an enum parameter + */ + parameterEnum: 'Success' | 'Warning' | 'Error'; + }; + url: '/api/v{api-version}/types'; +}; + +export type TypesResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Response is a simple string + */ + 201: string; + /** + * Response is a simple boolean + */ + 202: boolean; + /** + * Response is a simple object + */ + 203: { + [key: string]: unknown; + }; +}; + +export type TypesResponse = TypesResponses[keyof TypesResponses]; + +export type ComplexTypesData = { + body?: never; + path?: never; + query: { + /** + * Parameter containing object + */ + parameterObject: { + first?: { + second?: { + third?: string; + }; + }; + }; + /** + * This is a model with one string property + */ + parameterReference: { + /** + * This is a simple string property + */ + prop?: string; + }; + }; + url: '/api/v{api-version}/complex'; +}; + +export type ComplexTypesErrors = { + /** + * 400 server error + */ + 400: unknown; + /** + * 500 server error + */ + 500: unknown; +}; + +export type ComplexTypesResponses = { + /** + * Successful response + */ + 200: Array; +}; + +export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; + +export type CallWithResultFromHeaderData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/header'; +}; + +export type CallWithResultFromHeaderErrors = { + /** + * 400 server error + */ + 400: unknown; + /** + * 500 server error + */ + 500: unknown; +}; + +export type CallWithResultFromHeaderResponses = { + /** + * Successful response + */ + 200: unknown; +}; + +export type TestErrorCodeData = { + body?: never; + path?: never; + query: { + /** + * Status code to return + */ + status: string; + }; + url: '/api/v{api-version}/error'; +}; + +export type TestErrorCodeErrors = { + /** + * Custom message: Internal Server Error + */ + 500: unknown; + /** + * Custom message: Not Implemented + */ + 501: unknown; + /** + * Custom message: Bad Gateway + */ + 502: unknown; + /** + * Custom message: Service Unavailable + */ + 503: unknown; +}; + +export type TestErrorCodeResponses = { + /** + * Custom message: Successful response + */ + 200: unknown; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Data = { + body?: never; + path?: never; + query: { + /** + * Dummy input param + */ + nonAsciiParamæøåÆØÅöôêÊ: number; + }; + url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { + /** + * Successful response + */ + 200: NonAsciiStringæøåÆøÅöôêÊ字符串; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; + +export type PostApiVbyApiVersionBodyData = { + /** + * Body should not be unknown + */ + body: ParameterActivityParams; + path?: never; + query?: never; + url: '/api/v{api-version}/body'; +}; + +export type PostApiVbyApiVersionBodyErrors = { + /** + * Bad Request + */ + 400: FailureFailure; + /** + * Internal Server Error + */ + 500: FailureFailure; +}; + +export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; + +export type PostApiVbyApiVersionBodyResponses = { + /** + * OK + */ + 200: ResponsePostActivityResponse; +}; + +export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useMutation/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useMutation/@tanstack/react-query.gen.ts index fba7af785a..242b4bf86a 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useMutation/@tanstack/react-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useMutation/@tanstack/react-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, useMutation, type UseMutationOptions } from '@tanstack/react-query'; +import { type DefaultError, queryOptions, skipToken, useMutation, type UseMutationOptions, useQuery } from '@tanstack/react-query'; import { client } from '../client.gen'; import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); -export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const serviceWithEmptyTagOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const serviceWithEmptyTagOptions = (options?: Options) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useServiceWithEmptyTagQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(serviceWithEmptyTagOptions, options); + export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -104,8 +120,8 @@ export const useDeleteCallWithoutParametersAndResponseMutation = (mutationOption export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -113,10 +129,14 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithoutParametersAndResponseOptions, options); + export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -215,8 +235,8 @@ export const useCallWithWeirdParameterNamesMutation = (mutationOptions?: Partial export const callWithDefaultParametersQueryKey = (options: Options) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -224,10 +244,14 @@ export const callWithDefaultParametersOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithDefaultParametersOptions, options); + export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -278,8 +302,8 @@ export const useDuplicateNameMutation = (mutationOptions?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -287,10 +311,14 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); +export const useDuplicateName2Query = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(duplicateName2Options, options); + export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -325,8 +353,8 @@ export const useDuplicateName4Mutation = (mutationOptions?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -334,14 +362,18 @@ export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithNoContentResponseOptions, options); + export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -349,14 +381,18 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseAndNoContentResponseOptions, options); + export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -364,14 +400,18 @@ export const dummyAOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyAOptions, options); + export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -379,14 +419,18 @@ export const dummyBOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyBOptions, options); + export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -394,10 +438,14 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); +export const useCallWithResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseOptions, options); + export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -432,8 +480,8 @@ export const useCallWithResponsesMutation = (mutationOptions?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -441,14 +489,18 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); +export const useCollectionFormatQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(collectionFormatOptions, options); + export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -456,14 +508,18 @@ export const typesOptions = (options: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(typesOptions, options); + export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -471,10 +527,14 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); +export const useComplexTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(complexTypesOptions, options); + export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/@tanstack/react-query.gen.ts new file mode 100644 index 0000000000..1e6e02d645 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/@tanstack/react-query.gen.ts @@ -0,0 +1,509 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions } from '@tanstack/react-query'; + +import { client } from '../client.gen'; +import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; +import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyBData, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, GetCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TypesData, TypesResponse } from '../types.gen'; + +export type QueryKey = [ + Pick & { + _id: string; + _infinite?: boolean; + tags?: ReadonlyArray; + } +]; + +const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ + QueryKey[0] +] => { + const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; + if (infinite) { + params._infinite = infinite; + } + if (tags) { + params.tags = tags; + } + if (options?.body) { + params.body = options.body; + } + if (options?.headers) { + params.headers = options.headers; + } + if (options?.path) { + params.path = options.path; + } + if (options?.query) { + params.query = options.query; + } + return [params]; +}; + +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + +export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); + +export const serviceWithEmptyTagOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await serviceWithEmptyTag({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: serviceWithEmptyTagQueryKey(resolveOptions(options)) +}); + +export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await patchApiVbyApiVersionNoTag({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const fooWowMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await fooWow({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deleteCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); + +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await getCallWithoutParametersAndResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: getCallWithoutParametersAndResponseQueryKey(resolveOptions(options)) +}); + +export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await patchCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await putCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDescriptions({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithParametersMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithParameters({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithWeirdParameterNames({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithDefaultParametersQueryKey = (options: Options) => createQueryKey('callWithDefaultParameters', options); + +export const callWithDefaultParametersOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithDefaultParameters({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithDefaultParametersQueryKey(resolveOptions(options)) +}); + +export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDefaultOptionalParameters({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callToTestOrderOfParams({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateNameMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); + +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await duplicateName2({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) +}); + +export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName3({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName4({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); + +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithNoContentResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithNoContentResponseQueryKey(resolveOptions(options)) +}); + +export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); + +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithResponseAndNoContentResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithResponseAndNoContentResponseQueryKey(resolveOptions(options)) +}); + +export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); + +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await dummyA({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: dummyAQueryKey(resolveOptions(options)) +}); + +export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); + +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await dummyB({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: dummyBQueryKey(resolveOptions(options)) +}); + +export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); + +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) +}); + +export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDuplicateResponses({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithResponses({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); + +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await collectionFormat({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) +}); + +export const typesQueryKey = (options: Options) => createQueryKey('types', options); + +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await types({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: typesQueryKey(resolveOptions(options)) +}); + +export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); + +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await complexTypes({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) +}); + +export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithResultFromHeader({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await testErrorCode({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * Body should not be unknown + * + * Body should not be unknown + */ +export const postApiVbyApiVersionBodyMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postApiVbyApiVersionBody({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/client.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/client.gen.ts new file mode 100644 index 0000000000..25cd14eafb --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/client.gen.ts @@ -0,0 +1,16 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type ClientOptions, type Config, createClient, createConfig } from './client'; +import type { ClientOptions as ClientOptions2 } from './types.gen'; + +/** + * The `createClientConfig()` function will be called on client initialization + * and the returned object will become the client's initial configuration. + * + * You may want to initialize your client this way instead of calling + * `setConfig()`. This is useful for example if you're using Next.js + * to ensure your client always has the correct values. + */ +export type CreateClientConfig = (override?: Config) => Config & T>; + +export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/client.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/client.gen.ts new file mode 100644 index 0000000000..14dc0a0ec5 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/client.gen.ts @@ -0,0 +1,290 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { createSseClient } from '../core/serverSentEvents.gen'; +import type { HttpMethod } from '../core/types.gen'; +import { getValidRequestBody } from '../core/utils.gen'; +import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; +import { + buildUrl, + createConfig, + createInterceptors, + getParseAs, + mergeConfigs, + mergeHeaders, + setAuthParams, +} from './utils.gen'; + +type ReqInit = Omit & { + body?: any; + headers: ReturnType; +}; + +export const createClient = (config: Config = {}): Client => { + let _config = mergeConfigs(createConfig(), config); + + const getConfig = (): Config => ({ ..._config }); + + const setConfig = (config: Config): Config => { + _config = mergeConfigs(_config, config); + return getConfig(); + }; + + const interceptors = createInterceptors(); + + const beforeRequest = async (options: RequestOptions) => { + const opts = { + ..._config, + ...options, + fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, + headers: mergeHeaders(_config.headers, options.headers), + serializedBody: undefined as string | undefined, + }; + + if (opts.security) { + await setAuthParams({ + ...opts, + security: opts.security, + }); + } + + if (opts.requestValidator) { + await opts.requestValidator(opts); + } + + if (opts.body !== undefined && opts.bodySerializer) { + opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; + } + + // remove Content-Type header if body is empty to avoid sending invalid requests + if (opts.body === undefined || opts.serializedBody === '') { + opts.headers.delete('Content-Type'); + } + + const url = buildUrl(opts); + + return { opts, url }; + }; + + const request: Client['request'] = async (options) => { + // @ts-expect-error + const { opts, url } = await beforeRequest(options); + const requestInit: ReqInit = { + redirect: 'follow', + ...opts, + body: getValidRequestBody(opts), + }; + + let request = new Request(url, requestInit); + + for (const fn of interceptors.request.fns) { + if (fn) { + request = await fn(request, opts); + } + } + + // fetch must be assigned here, otherwise it would throw the error: + // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation + const _fetch = opts.fetch!; + let response: Response; + + try { + response = await _fetch(request); + } catch (error) { + // Handle fetch exceptions (AbortError, network errors, etc.) + let finalError = error; + + for (const fn of interceptors.error.fns) { + if (fn) { + finalError = (await fn(error, undefined as any, request, opts)) as unknown; + } + } + + finalError = finalError || ({} as unknown); + + if (opts.throwOnError) { + throw finalError; + } + + // Return error response + return opts.responseStyle === 'data' + ? undefined + : { + error: finalError, + request, + response: undefined as any, + }; + } + + for (const fn of interceptors.response.fns) { + if (fn) { + response = await fn(response, request, opts); + } + } + + const result = { + request, + response, + }; + + if (response.ok) { + const parseAs = + (opts.parseAs === 'auto' + ? getParseAs(response.headers.get('Content-Type')) + : opts.parseAs) ?? 'json'; + + if (response.status === 204 || response.headers.get('Content-Length') === '0') { + let emptyData: any; + switch (parseAs) { + case 'arrayBuffer': + case 'blob': + case 'text': + emptyData = await response[parseAs](); + break; + case 'formData': + emptyData = new FormData(); + break; + case 'stream': + emptyData = response.body; + break; + case 'json': + default: + emptyData = {}; + break; + } + return opts.responseStyle === 'data' + ? emptyData + : { + data: emptyData, + ...result, + }; + } + + let data: any; + switch (parseAs) { + case 'arrayBuffer': + case 'blob': + case 'formData': + case 'text': + data = await response[parseAs](); + break; + case 'json': { + // Some servers return 200 with no Content-Length and empty body. + // response.json() would throw; read as text and parse if non-empty. + const text = await response.text(); + data = text ? JSON.parse(text) : {}; + break; + } + case 'stream': + return opts.responseStyle === 'data' + ? response.body + : { + data: response.body, + ...result, + }; + } + + if (parseAs === 'json') { + if (opts.responseValidator) { + await opts.responseValidator(data); + } + + if (opts.responseTransformer) { + data = await opts.responseTransformer(data); + } + } + + return opts.responseStyle === 'data' + ? data + : { + data, + ...result, + }; + } + + const textError = await response.text(); + let jsonError: unknown; + + try { + jsonError = JSON.parse(textError); + } catch { + // noop + } + + const error = jsonError ?? textError; + let finalError = error; + + for (const fn of interceptors.error.fns) { + if (fn) { + finalError = (await fn(error, response, request, opts)) as string; + } + } + + finalError = finalError || ({} as string); + + if (opts.throwOnError) { + throw finalError; + } + + // TODO: we probably want to return error and improve types + return opts.responseStyle === 'data' + ? undefined + : { + error: finalError, + ...result, + }; + }; + + const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => + request({ ...options, method }); + + const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { + const { opts, url } = await beforeRequest(options); + return createSseClient({ + ...opts, + body: opts.body as BodyInit | null | undefined, + headers: opts.headers as unknown as Record, + method, + onRequest: async (url, init) => { + let request = new Request(url, init); + for (const fn of interceptors.request.fns) { + if (fn) { + request = await fn(request, opts); + } + } + return request; + }, + serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, + url, + }); + }; + + const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); + + return { + buildUrl: _buildUrl, + connect: makeMethodFn('CONNECT'), + delete: makeMethodFn('DELETE'), + get: makeMethodFn('GET'), + getConfig, + head: makeMethodFn('HEAD'), + interceptors, + options: makeMethodFn('OPTIONS'), + patch: makeMethodFn('PATCH'), + post: makeMethodFn('POST'), + put: makeMethodFn('PUT'), + request, + setConfig, + sse: { + connect: makeSseFn('CONNECT'), + delete: makeSseFn('DELETE'), + get: makeSseFn('GET'), + head: makeSseFn('HEAD'), + options: makeSseFn('OPTIONS'), + patch: makeSseFn('PATCH'), + post: makeSseFn('POST'), + put: makeSseFn('PUT'), + trace: makeSseFn('TRACE'), + }, + trace: makeMethodFn('TRACE'), + } as Client; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/index.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/index.ts new file mode 100644 index 0000000000..b295edeca0 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/index.ts @@ -0,0 +1,25 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type { Auth } from '../core/auth.gen'; +export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; +export { + formDataBodySerializer, + jsonBodySerializer, + urlSearchParamsBodySerializer, +} from '../core/bodySerializer.gen'; +export { buildClientParams } from '../core/params.gen'; +export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; +export { createClient } from './client.gen'; +export type { + Client, + ClientOptions, + Config, + CreateClientConfig, + Options, + RequestOptions, + RequestResult, + ResolvedRequestOptions, + ResponseStyle, + TDataShape, +} from './types.gen'; +export { createConfig, mergeHeaders } from './utils.gen'; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/types.gen.ts new file mode 100644 index 0000000000..a3f8616511 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/types.gen.ts @@ -0,0 +1,214 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Auth } from '../core/auth.gen'; +import type { + ServerSentEventsOptions, + ServerSentEventsResult, +} from '../core/serverSentEvents.gen'; +import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; +import type { Middleware } from './utils.gen'; + +export type ResponseStyle = 'data' | 'fields'; + +export interface Config + extends Omit, CoreConfig { + /** + * Base URL for all requests made by this client. + */ + baseUrl?: T['baseUrl']; + /** + * Fetch API implementation. You can use this option to provide a custom + * fetch instance. + * + * @default globalThis.fetch + */ + fetch?: typeof fetch; + /** + * Please don't use the Fetch client for Next.js applications. The `next` + * options won't have any effect. + * + * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. + */ + next?: never; + /** + * Return the response data parsed in a specified format. By default, `auto` + * will infer the appropriate method from the `Content-Type` response header. + * You can override this behavior with any of the {@link Body} methods. + * Select `stream` if you don't want to parse response data at all. + * + * @default 'auto' + */ + parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; + /** + * Should we return only data or multiple fields (data, error, response, etc.)? + * + * @default 'fields' + */ + responseStyle?: ResponseStyle; + /** + * Throw an error instead of returning it in the response? + * + * @default false + */ + throwOnError?: T['throwOnError']; +} + +export interface RequestOptions< + TData = unknown, + TResponseStyle extends ResponseStyle = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, +> + extends + Config<{ + responseStyle: TResponseStyle; + throwOnError: ThrowOnError; + }>, + Pick< + ServerSentEventsOptions, + | 'onRequest' + | 'onSseError' + | 'onSseEvent' + | 'sseDefaultRetryDelay' + | 'sseMaxRetryAttempts' + | 'sseMaxRetryDelay' + > { + /** + * Any body that you want to add to your request. + * + * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} + */ + body?: unknown; + path?: Record; + query?: Record; + /** + * Security mechanism(s) to use for the request. + */ + security?: ReadonlyArray; + url: Url; +} + +export interface ResolvedRequestOptions< + TResponseStyle extends ResponseStyle = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, +> extends RequestOptions { + serializedBody?: string; +} + +export type RequestResult< + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = boolean, + TResponseStyle extends ResponseStyle = 'fields', +> = ThrowOnError extends true + ? Promise< + TResponseStyle extends 'data' + ? TData extends Record + ? TData[keyof TData] + : TData + : { + data: TData extends Record ? TData[keyof TData] : TData; + request: Request; + response: Response; + } + > + : Promise< + TResponseStyle extends 'data' + ? (TData extends Record ? TData[keyof TData] : TData) | undefined + : ( + | { + data: TData extends Record ? TData[keyof TData] : TData; + error: undefined; + } + | { + data: undefined; + error: TError extends Record ? TError[keyof TError] : TError; + } + ) & { + request: Request; + response: Response; + } + >; + +export interface ClientOptions { + baseUrl?: string; + responseStyle?: ResponseStyle; + throwOnError?: boolean; +} + +type MethodFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'>, +) => RequestResult; + +type SseFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'>, +) => Promise>; + +type RequestFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'> & + Pick>, 'method'>, +) => RequestResult; + +type BuildUrlFn = < + TData extends { + body?: unknown; + path?: Record; + query?: Record; + url: string; + }, +>( + options: TData & Options, +) => string; + +export type Client = CoreClient & { + interceptors: Middleware; +}; + +/** + * The `createClientConfig()` function will be called on client initialization + * and the returned object will become the client's initial configuration. + * + * You may want to initialize your client this way instead of calling + * `setConfig()`. This is useful for example if you're using Next.js + * to ensure your client always has the correct values. + */ +export type CreateClientConfig = ( + override?: Config, +) => Config & T>; + +export interface TDataShape { + body?: unknown; + headers?: unknown; + path?: unknown; + query?: unknown; + url: string; +} + +type OmitKeys = Pick>; + +export type Options< + TData extends TDataShape = TDataShape, + ThrowOnError extends boolean = boolean, + TResponse = unknown, + TResponseStyle extends ResponseStyle = 'fields', +> = OmitKeys< + RequestOptions, + 'body' | 'path' | 'query' | 'url' +> & + ([TData] extends [never] ? unknown : Omit); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/utils.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/utils.gen.ts new file mode 100644 index 0000000000..b4bd2435ce --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/utils.gen.ts @@ -0,0 +1,316 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { getAuthToken } from '../core/auth.gen'; +import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; +import { jsonBodySerializer } from '../core/bodySerializer.gen'; +import { + serializeArrayParam, + serializeObjectParam, + serializePrimitiveParam, +} from '../core/pathSerializer.gen'; +import { getUrl } from '../core/utils.gen'; +import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; + +export const createQuerySerializer = ({ + parameters = {}, + ...args +}: QuerySerializerOptions = {}) => { + const querySerializer = (queryParams: T) => { + const search: string[] = []; + if (queryParams && typeof queryParams === 'object') { + for (const name in queryParams) { + const value = queryParams[name]; + + if (value === undefined || value === null) { + continue; + } + + const options = parameters[name] || args; + + if (Array.isArray(value)) { + const serializedArray = serializeArrayParam({ + allowReserved: options.allowReserved, + explode: true, + name, + style: 'form', + value, + ...options.array, + }); + if (serializedArray) search.push(serializedArray); + } else if (typeof value === 'object') { + const serializedObject = serializeObjectParam({ + allowReserved: options.allowReserved, + explode: true, + name, + style: 'deepObject', + value: value as Record, + ...options.object, + }); + if (serializedObject) search.push(serializedObject); + } else { + const serializedPrimitive = serializePrimitiveParam({ + allowReserved: options.allowReserved, + name, + value: value as string, + }); + if (serializedPrimitive) search.push(serializedPrimitive); + } + } + } + return search.join('&'); + }; + return querySerializer; +}; + +/** + * Infers parseAs value from provided Content-Type header. + */ +export const getParseAs = (contentType: string | null): Exclude => { + if (!contentType) { + // If no Content-Type header is provided, the best we can do is return the raw response body, + // which is effectively the same as the 'stream' option. + return 'stream'; + } + + const cleanContent = contentType.split(';')[0]?.trim(); + + if (!cleanContent) { + return; + } + + if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { + return 'json'; + } + + if (cleanContent === 'multipart/form-data') { + return 'formData'; + } + + if ( + ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) + ) { + return 'blob'; + } + + if (cleanContent.startsWith('text/')) { + return 'text'; + } + + return; +}; + +const checkForExistence = ( + options: Pick & { + headers: Headers; + }, + name?: string, +): boolean => { + if (!name) { + return false; + } + if ( + options.headers.has(name) || + options.query?.[name] || + options.headers.get('Cookie')?.includes(`${name}=`) + ) { + return true; + } + return false; +}; + +export const setAuthParams = async ({ + security, + ...options +}: Pick, 'security'> & + Pick & { + headers: Headers; + }) => { + for (const auth of security) { + if (checkForExistence(options, auth.name)) { + continue; + } + + const token = await getAuthToken(auth, options.auth); + + if (!token) { + continue; + } + + const name = auth.name ?? 'Authorization'; + + switch (auth.in) { + case 'query': + if (!options.query) { + options.query = {}; + } + options.query[name] = token; + break; + case 'cookie': + options.headers.append('Cookie', `${name}=${token}`); + break; + case 'header': + default: + options.headers.set(name, token); + break; + } + } +}; + +export const buildUrl: Client['buildUrl'] = (options) => + getUrl({ + baseUrl: options.baseUrl as string, + path: options.path, + query: options.query, + querySerializer: + typeof options.querySerializer === 'function' + ? options.querySerializer + : createQuerySerializer(options.querySerializer), + url: options.url, + }); + +export const mergeConfigs = (a: Config, b: Config): Config => { + const config = { ...a, ...b }; + if (config.baseUrl?.endsWith('/')) { + config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); + } + config.headers = mergeHeaders(a.headers, b.headers); + return config; +}; + +const headersEntries = (headers: Headers): Array<[string, string]> => { + const entries: Array<[string, string]> = []; + headers.forEach((value, key) => { + entries.push([key, value]); + }); + return entries; +}; + +export const mergeHeaders = ( + ...headers: Array['headers'] | undefined> +): Headers => { + const mergedHeaders = new Headers(); + for (const header of headers) { + if (!header) { + continue; + } + + const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); + + for (const [key, value] of iterator) { + if (value === null) { + mergedHeaders.delete(key); + } else if (Array.isArray(value)) { + for (const v of value) { + mergedHeaders.append(key, v as string); + } + } else if (value !== undefined) { + // assume object headers are meant to be JSON stringified, i.e. their + // content value in OpenAPI specification is 'application/json' + mergedHeaders.set( + key, + typeof value === 'object' ? JSON.stringify(value) : (value as string), + ); + } + } + } + return mergedHeaders; +}; + +type ErrInterceptor = ( + error: Err, + response: Res, + request: Req, + options: Options, +) => Err | Promise; + +type ReqInterceptor = (request: Req, options: Options) => Req | Promise; + +type ResInterceptor = ( + response: Res, + request: Req, + options: Options, +) => Res | Promise; + +class Interceptors { + fns: Array = []; + + clear(): void { + this.fns = []; + } + + eject(id: number | Interceptor): void { + const index = this.getInterceptorIndex(id); + if (this.fns[index]) { + this.fns[index] = null; + } + } + + exists(id: number | Interceptor): boolean { + const index = this.getInterceptorIndex(id); + return Boolean(this.fns[index]); + } + + getInterceptorIndex(id: number | Interceptor): number { + if (typeof id === 'number') { + return this.fns[id] ? id : -1; + } + return this.fns.indexOf(id); + } + + update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { + const index = this.getInterceptorIndex(id); + if (this.fns[index]) { + this.fns[index] = fn; + return id; + } + return false; + } + + use(fn: Interceptor): number { + this.fns.push(fn); + return this.fns.length - 1; + } +} + +export interface Middleware { + error: Interceptors>; + request: Interceptors>; + response: Interceptors>; +} + +export const createInterceptors = (): Middleware< + Req, + Res, + Err, + Options +> => ({ + error: new Interceptors>(), + request: new Interceptors>(), + response: new Interceptors>(), +}); + +const defaultQuerySerializer = createQuerySerializer({ + allowReserved: false, + array: { + explode: true, + style: 'form', + }, + object: { + explode: true, + style: 'deepObject', + }, +}); + +const defaultHeaders = { + 'Content-Type': 'application/json', +}; + +export const createConfig = ( + override: Config & T> = {}, +): Config & T> => ({ + ...jsonBodySerializer, + headers: defaultHeaders, + parseAs: 'auto', + querySerializer: defaultQuerySerializer, + ...override, +}); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/auth.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/auth.gen.ts new file mode 100644 index 0000000000..3ebf994788 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/auth.gen.ts @@ -0,0 +1,41 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type AuthToken = string | undefined; + +export interface Auth { + /** + * Which part of the request do we use to send the auth? + * + * @default 'header' + */ + in?: 'header' | 'query' | 'cookie'; + /** + * Header or query parameter name. + * + * @default 'Authorization' + */ + name?: string; + scheme?: 'basic' | 'bearer'; + type: 'apiKey' | 'http'; +} + +export const getAuthToken = async ( + auth: Auth, + callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, +): Promise => { + const token = typeof callback === 'function' ? await callback(auth) : callback; + + if (!token) { + return; + } + + if (auth.scheme === 'bearer') { + return `Bearer ${token}`; + } + + if (auth.scheme === 'basic') { + return `Basic ${btoa(token)}`; + } + + return token; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/bodySerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/bodySerializer.gen.ts new file mode 100644 index 0000000000..67daca60f8 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/bodySerializer.gen.ts @@ -0,0 +1,82 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; + +export type QuerySerializer = (query: Record) => string; + +export type BodySerializer = (body: unknown) => unknown; + +type QuerySerializerOptionsObject = { + allowReserved?: boolean; + array?: Partial>; + object?: Partial>; +}; + +export type QuerySerializerOptions = QuerySerializerOptionsObject & { + /** + * Per-parameter serialization overrides. When provided, these settings + * override the global array/object settings for specific parameter names. + */ + parameters?: Record; +}; + +const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { + if (typeof value === 'string' || value instanceof Blob) { + data.append(key, value); + } else if (value instanceof Date) { + data.append(key, value.toISOString()); + } else { + data.append(key, JSON.stringify(value)); + } +}; + +const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { + if (typeof value === 'string') { + data.append(key, value); + } else { + data.append(key, JSON.stringify(value)); + } +}; + +export const formDataBodySerializer = { + bodySerializer: (body: unknown): FormData => { + const data = new FormData(); + + Object.entries(body as Record).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + if (Array.isArray(value)) { + value.forEach((v) => serializeFormDataPair(data, key, v)); + } else { + serializeFormDataPair(data, key, value); + } + }); + + return data; + }, +}; + +export const jsonBodySerializer = { + bodySerializer: (body: unknown): string => + JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), +}; + +export const urlSearchParamsBodySerializer = { + bodySerializer: (body: unknown): string => { + const data = new URLSearchParams(); + + Object.entries(body as Record).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + if (Array.isArray(value)) { + value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); + } else { + serializeUrlSearchParamsPair(data, key, value); + } + }); + + return data.toString(); + }, +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/params.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/params.gen.ts new file mode 100644 index 0000000000..7955601a5c --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/params.gen.ts @@ -0,0 +1,169 @@ +// This file is auto-generated by @hey-api/openapi-ts + +type Slot = 'body' | 'headers' | 'path' | 'query'; + +export type Field = + | { + in: Exclude; + /** + * Field name. This is the name we want the user to see and use. + */ + key: string; + /** + * Field mapped name. This is the name we want to use in the request. + * If omitted, we use the same value as `key`. + */ + map?: string; + } + | { + in: Extract; + /** + * Key isn't required for bodies. + */ + key?: string; + map?: string; + } + | { + /** + * Field name. This is the name we want the user to see and use. + */ + key: string; + /** + * Field mapped name. This is the name we want to use in the request. + * If `in` is omitted, `map` aliases `key` to the transport layer. + */ + map: Slot; + }; + +export interface Fields { + allowExtra?: Partial>; + args?: ReadonlyArray; +} + +export type FieldsConfig = ReadonlyArray; + +const extraPrefixesMap: Record = { + $body_: 'body', + $headers_: 'headers', + $path_: 'path', + $query_: 'query', +}; +const extraPrefixes = Object.entries(extraPrefixesMap); + +type KeyMap = Map< + string, + | { + in: Slot; + map?: string; + } + | { + in?: never; + map: Slot; + } +>; + +const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { + if (!map) { + map = new Map(); + } + + for (const config of fields) { + if ('in' in config) { + if (config.key) { + map.set(config.key, { + in: config.in, + map: config.map, + }); + } + } else if ('key' in config) { + map.set(config.key, { + map: config.map, + }); + } else if (config.args) { + buildKeyMap(config.args, map); + } + } + + return map; +}; + +interface Params { + body: unknown; + headers: Record; + path: Record; + query: Record; +} + +const stripEmptySlots = (params: Params) => { + for (const [slot, value] of Object.entries(params)) { + if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { + delete params[slot as Slot]; + } + } +}; + +export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { + const params: Params = { + body: {}, + headers: {}, + path: {}, + query: {}, + }; + + const map = buildKeyMap(fields); + + let config: FieldsConfig[number] | undefined; + + for (const [index, arg] of args.entries()) { + if (fields[index]) { + config = fields[index]; + } + + if (!config) { + continue; + } + + if ('in' in config) { + if (config.key) { + const field = map.get(config.key)!; + const name = field.map || config.key; + if (field.in) { + (params[field.in] as Record)[name] = arg; + } + } else { + params.body = arg; + } + } else { + for (const [key, value] of Object.entries(arg ?? {})) { + const field = map.get(key); + + if (field) { + if (field.in) { + const name = field.map || key; + (params[field.in] as Record)[name] = value; + } else { + params[field.map] = value; + } + } else { + const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); + + if (extra) { + const [prefix, slot] = extra; + (params[slot] as Record)[key.slice(prefix.length)] = value; + } else if ('allowExtra' in config && config.allowExtra) { + for (const [slot, allowed] of Object.entries(config.allowExtra)) { + if (allowed) { + (params[slot as Slot] as Record)[key] = value; + break; + } + } + } + } + } + } + } + + stripEmptySlots(params); + + return params; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/pathSerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/pathSerializer.gen.ts new file mode 100644 index 0000000000..994b2848c6 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/pathSerializer.gen.ts @@ -0,0 +1,171 @@ +// This file is auto-generated by @hey-api/openapi-ts + +interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} + +interface SerializePrimitiveOptions { + allowReserved?: boolean; + name: string; +} + +export interface SerializerOptions { + /** + * @default true + */ + explode: boolean; + style: T; +} + +export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; +export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; +type MatrixStyle = 'label' | 'matrix' | 'simple'; +export type ObjectStyle = 'form' | 'deepObject'; +type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; + +interface SerializePrimitiveParam extends SerializePrimitiveOptions { + value: string; +} + +export const separatorArrayExplode = (style: ArraySeparatorStyle) => { + switch (style) { + case 'label': + return '.'; + case 'matrix': + return ';'; + case 'simple': + return ','; + default: + return '&'; + } +}; + +export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { + switch (style) { + case 'form': + return ','; + case 'pipeDelimited': + return '|'; + case 'spaceDelimited': + return '%20'; + default: + return ','; + } +}; + +export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { + switch (style) { + case 'label': + return '.'; + case 'matrix': + return ';'; + case 'simple': + return ','; + default: + return '&'; + } +}; + +export const serializeArrayParam = ({ + allowReserved, + explode, + name, + style, + value, +}: SerializeOptions & { + value: unknown[]; +}) => { + if (!explode) { + const joinedValues = ( + allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) + ).join(separatorArrayNoExplode(style)); + switch (style) { + case 'label': + return `.${joinedValues}`; + case 'matrix': + return `;${name}=${joinedValues}`; + case 'simple': + return joinedValues; + default: + return `${name}=${joinedValues}`; + } + } + + const separator = separatorArrayExplode(style); + const joinedValues = value + .map((v) => { + if (style === 'label' || style === 'simple') { + return allowReserved ? v : encodeURIComponent(v as string); + } + + return serializePrimitiveParam({ + allowReserved, + name, + value: v as string, + }); + }) + .join(separator); + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; +}; + +export const serializePrimitiveParam = ({ + allowReserved, + name, + value, +}: SerializePrimitiveParam) => { + if (value === undefined || value === null) { + return ''; + } + + if (typeof value === 'object') { + throw new Error( + 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', + ); + } + + return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; +}; + +export const serializeObjectParam = ({ + allowReserved, + explode, + name, + style, + value, + valueOnly, +}: SerializeOptions & { + value: Record | Date; + valueOnly?: boolean; +}) => { + if (value instanceof Date) { + return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; + } + + if (style !== 'deepObject' && !explode) { + let values: string[] = []; + Object.entries(value).forEach(([key, v]) => { + values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; + }); + const joinedValues = values.join(','); + switch (style) { + case 'form': + return `${name}=${joinedValues}`; + case 'label': + return `.${joinedValues}`; + case 'matrix': + return `;${name}=${joinedValues}`; + default: + return joinedValues; + } + } + + const separator = separatorObjectExplode(style); + const joinedValues = Object.entries(value) + .map(([key, v]) => + serializePrimitiveParam({ + allowReserved, + name: style === 'deepObject' ? `${name}[${key}]` : key, + value: v as string, + }), + ) + .join(separator); + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/queryKeySerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/queryKeySerializer.gen.ts new file mode 100644 index 0000000000..5000df606f --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/queryKeySerializer.gen.ts @@ -0,0 +1,117 @@ +// This file is auto-generated by @hey-api/openapi-ts + +/** + * JSON-friendly union that mirrors what Pinia Colada can hash. + */ +export type JsonValue = + | null + | string + | number + | boolean + | JsonValue[] + | { [key: string]: JsonValue }; + +/** + * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. + */ +export const queryKeyJsonReplacer = (_key: string, value: unknown) => { + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { + return undefined; + } + if (typeof value === 'bigint') { + return value.toString(); + } + if (value instanceof Date) { + return value.toISOString(); + } + return value; +}; + +/** + * Safely stringifies a value and parses it back into a JsonValue. + */ +export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { + try { + const json = JSON.stringify(input, queryKeyJsonReplacer); + if (json === undefined) { + return undefined; + } + return JSON.parse(json) as JsonValue; + } catch { + return undefined; + } +}; + +/** + * Detects plain objects (including objects with a null prototype). + */ +const isPlainObject = (value: unknown): value is Record => { + if (value === null || typeof value !== 'object') { + return false; + } + const prototype = Object.getPrototypeOf(value as object); + return prototype === Object.prototype || prototype === null; +}; + +/** + * Turns URLSearchParams into a sorted JSON object for deterministic keys. + */ +const serializeSearchParams = (params: URLSearchParams): JsonValue => { + const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); + const result: Record = {}; + + for (const [key, value] of entries) { + const existing = result[key]; + if (existing === undefined) { + result[key] = value; + continue; + } + + if (Array.isArray(existing)) { + (existing as string[]).push(value); + } else { + result[key] = [existing, value]; + } + } + + return result; +}; + +/** + * Normalizes any accepted value into a JSON-friendly shape for query keys. + */ +export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { + if (value === null) { + return null; + } + + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return value; + } + + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { + return undefined; + } + + if (typeof value === 'bigint') { + return value.toString(); + } + + if (value instanceof Date) { + return value.toISOString(); + } + + if (Array.isArray(value)) { + return stringifyToJsonValue(value); + } + + if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { + return serializeSearchParams(value); + } + + if (isPlainObject(value)) { + return stringifyToJsonValue(value); + } + + return undefined; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/serverSentEvents.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/serverSentEvents.gen.ts new file mode 100644 index 0000000000..6aa6cf02a4 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/serverSentEvents.gen.ts @@ -0,0 +1,243 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Config } from './types.gen'; + +export type ServerSentEventsOptions = Omit & + Pick & { + /** + * Fetch API implementation. You can use this option to provide a custom + * fetch instance. + * + * @default globalThis.fetch + */ + fetch?: typeof fetch; + /** + * Implementing clients can call request interceptors inside this hook. + */ + onRequest?: (url: string, init: RequestInit) => Promise; + /** + * Callback invoked when a network or parsing error occurs during streaming. + * + * This option applies only if the endpoint returns a stream of events. + * + * @param error The error that occurred. + */ + onSseError?: (error: unknown) => void; + /** + * Callback invoked when an event is streamed from the server. + * + * This option applies only if the endpoint returns a stream of events. + * + * @param event Event streamed from the server. + * @returns Nothing (void). + */ + onSseEvent?: (event: StreamEvent) => void; + serializedBody?: RequestInit['body']; + /** + * Default retry delay in milliseconds. + * + * This option applies only if the endpoint returns a stream of events. + * + * @default 3000 + */ + sseDefaultRetryDelay?: number; + /** + * Maximum number of retry attempts before giving up. + */ + sseMaxRetryAttempts?: number; + /** + * Maximum retry delay in milliseconds. + * + * Applies only when exponential backoff is used. + * + * This option applies only if the endpoint returns a stream of events. + * + * @default 30000 + */ + sseMaxRetryDelay?: number; + /** + * Optional sleep function for retry backoff. + * + * Defaults to using `setTimeout`. + */ + sseSleepFn?: (ms: number) => Promise; + url: string; + }; + +export interface StreamEvent { + data: TData; + event?: string; + id?: string; + retry?: number; +} + +export type ServerSentEventsResult = { + stream: AsyncGenerator< + TData extends Record ? TData[keyof TData] : TData, + TReturn, + TNext + >; +}; + +export const createSseClient = ({ + onRequest, + onSseError, + onSseEvent, + responseTransformer, + responseValidator, + sseDefaultRetryDelay, + sseMaxRetryAttempts, + sseMaxRetryDelay, + sseSleepFn, + url, + ...options +}: ServerSentEventsOptions): ServerSentEventsResult => { + let lastEventId: string | undefined; + + const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + + const createStream = async function* () { + let retryDelay: number = sseDefaultRetryDelay ?? 3000; + let attempt = 0; + const signal = options.signal ?? new AbortController().signal; + + while (true) { + if (signal.aborted) break; + + attempt++; + + const headers = + options.headers instanceof Headers + ? options.headers + : new Headers(options.headers as Record | undefined); + + if (lastEventId !== undefined) { + headers.set('Last-Event-ID', lastEventId); + } + + try { + const requestInit: RequestInit = { + redirect: 'follow', + ...options, + body: options.serializedBody, + headers, + signal, + }; + let request = new Request(url, requestInit); + if (onRequest) { + request = await onRequest(url, requestInit); + } + // fetch must be assigned here, otherwise it would throw the error: + // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation + const _fetch = options.fetch ?? globalThis.fetch; + const response = await _fetch(request); + + if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); + + if (!response.body) throw new Error('No body in SSE response'); + + const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); + + let buffer = ''; + + const abortHandler = () => { + try { + reader.cancel(); + } catch { + // noop + } + }; + + signal.addEventListener('abort', abortHandler); + + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + buffer += value; + // Normalize line endings: CRLF -> LF, then CR -> LF + buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); + + const chunks = buffer.split('\n\n'); + buffer = chunks.pop() ?? ''; + + for (const chunk of chunks) { + const lines = chunk.split('\n'); + const dataLines: Array = []; + let eventName: string | undefined; + + for (const line of lines) { + if (line.startsWith('data:')) { + dataLines.push(line.replace(/^data:\s*/, '')); + } else if (line.startsWith('event:')) { + eventName = line.replace(/^event:\s*/, ''); + } else if (line.startsWith('id:')) { + lastEventId = line.replace(/^id:\s*/, ''); + } else if (line.startsWith('retry:')) { + const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); + if (!Number.isNaN(parsed)) { + retryDelay = parsed; + } + } + } + + let data: unknown; + let parsedJson = false; + + if (dataLines.length) { + const rawData = dataLines.join('\n'); + try { + data = JSON.parse(rawData); + parsedJson = true; + } catch { + data = rawData; + } + } + + if (parsedJson) { + if (responseValidator) { + await responseValidator(data); + } + + if (responseTransformer) { + data = await responseTransformer(data); + } + } + + onSseEvent?.({ + data, + event: eventName, + id: lastEventId, + retry: retryDelay, + }); + + if (dataLines.length) { + yield data as any; + } + } + } + } finally { + signal.removeEventListener('abort', abortHandler); + reader.releaseLock(); + } + + break; // exit loop on normal completion + } catch (error) { + // connection failed or aborted; retry after delay + onSseError?.(error); + + if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { + break; // stop after firing error + } + + // exponential backoff: double retry each attempt, cap at 30s + const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); + await sleep(backoff); + } + } + }; + + const stream = createStream(); + + return { stream }; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/types.gen.ts new file mode 100644 index 0000000000..97463257e4 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/types.gen.ts @@ -0,0 +1,104 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Auth, AuthToken } from './auth.gen'; +import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; + +export type HttpMethod = + | 'connect' + | 'delete' + | 'get' + | 'head' + | 'options' + | 'patch' + | 'post' + | 'put' + | 'trace'; + +export type Client< + RequestFn = never, + Config = unknown, + MethodFn = never, + BuildUrlFn = never, + SseFn = never, +> = { + /** + * Returns the final request URL. + */ + buildUrl: BuildUrlFn; + getConfig: () => Config; + request: RequestFn; + setConfig: (config: Config) => Config; +} & { + [K in HttpMethod]: MethodFn; +} & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); + +export interface Config { + /** + * Auth token or a function returning auth token. The resolved value will be + * added to the request payload as defined by its `security` array. + */ + auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; + /** + * A function for serializing request body parameter. By default, + * {@link JSON.stringify()} will be used. + */ + bodySerializer?: BodySerializer | null; + /** + * An object containing any HTTP headers that you want to pre-populate your + * `Headers` object with. + * + * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} + */ + headers?: + | RequestInit['headers'] + | Record< + string, + string | number | boolean | (string | number | boolean)[] | null | undefined | unknown + >; + /** + * The request method. + * + * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} + */ + method?: Uppercase; + /** + * A function for serializing request query parameters. By default, arrays + * will be exploded in form style, objects will be exploded in deepObject + * style, and reserved characters are percent-encoded. + * + * This method will have no effect if the native `paramsSerializer()` Axios + * API function is used. + * + * {@link https://swagger.io/docs/specification/serialization/#query View examples} + */ + querySerializer?: QuerySerializer | QuerySerializerOptions; + /** + * A function validating request data. This is useful if you want to ensure + * the request conforms to the desired shape, so it can be safely sent to + * the server. + */ + requestValidator?: (data: unknown) => Promise; + /** + * A function transforming response data before it's returned. This is useful + * for post-processing data, e.g. converting ISO strings into Date objects. + */ + responseTransformer?: (data: unknown) => Promise; + /** + * A function validating response data. This is useful if you want to ensure + * the response conforms to the desired shape, so it can be safely passed to + * the transformers and returned to the user. + */ + responseValidator?: (data: unknown) => Promise; +} + +type IsExactlyNeverOrNeverUndefined = [T] extends [never] + ? true + : [T] extends [never | undefined] + ? [undefined] extends [T] + ? false + : true + : false; + +export type OmitNever> = { + [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/utils.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/utils.gen.ts new file mode 100644 index 0000000000..e7ddbe3541 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/utils.gen.ts @@ -0,0 +1,140 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; +import { + type ArraySeparatorStyle, + serializeArrayParam, + serializeObjectParam, + serializePrimitiveParam, +} from './pathSerializer.gen'; + +export interface PathSerializer { + path: Record; + url: string; +} + +export const PATH_PARAM_RE = /\{[^{}]+\}/g; + +export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { + let url = _url; + const matches = _url.match(PATH_PARAM_RE); + if (matches) { + for (const match of matches) { + let explode = false; + let name = match.substring(1, match.length - 1); + let style: ArraySeparatorStyle = 'simple'; + + if (name.endsWith('*')) { + explode = true; + name = name.substring(0, name.length - 1); + } + + if (name.startsWith('.')) { + name = name.substring(1); + style = 'label'; + } else if (name.startsWith(';')) { + name = name.substring(1); + style = 'matrix'; + } + + const value = path[name]; + + if (value === undefined || value === null) { + continue; + } + + if (Array.isArray(value)) { + url = url.replace(match, serializeArrayParam({ explode, name, style, value })); + continue; + } + + if (typeof value === 'object') { + url = url.replace( + match, + serializeObjectParam({ + explode, + name, + style, + value: value as Record, + valueOnly: true, + }), + ); + continue; + } + + if (style === 'matrix') { + url = url.replace( + match, + `;${serializePrimitiveParam({ + name, + value: value as string, + })}`, + ); + continue; + } + + const replaceValue = encodeURIComponent( + style === 'label' ? `.${value as string}` : (value as string), + ); + url = url.replace(match, replaceValue); + } + } + return url; +}; + +export const getUrl = ({ + baseUrl, + path, + query, + querySerializer, + url: _url, +}: { + baseUrl?: string; + path?: Record; + query?: Record; + querySerializer: QuerySerializer; + url: string; +}) => { + const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; + let url = (baseUrl ?? '') + pathUrl; + if (path) { + url = defaultPathSerializer({ path, url }); + } + let search = query ? querySerializer(query) : ''; + if (search.startsWith('?')) { + search = search.substring(1); + } + if (search) { + url += `?${search}`; + } + return url; +}; + +export function getValidRequestBody(options: { + body?: unknown; + bodySerializer?: BodySerializer | null; + serializedBody?: unknown; +}) { + const hasBody = options.body !== undefined; + const isSerializedBody = hasBody && options.bodySerializer; + + if (isSerializedBody) { + if ('serializedBody' in options) { + const hasSerializedBody = + options.serializedBody !== undefined && options.serializedBody !== ''; + + return hasSerializedBody ? options.serializedBody : null; + } + + // not all clients implement a serializedBody property (i.e. client-axios) + return options.body !== '' ? options.body : null; + } + + // plain/text body + if (hasBody) { + return options.body; + } + + // no body was provided + return undefined; +} diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/index.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/index.ts new file mode 100644 index 0000000000..ee6d0288c0 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/index.ts @@ -0,0 +1,4 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from './sdk.gen'; +export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/sdk.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/sdk.gen.ts new file mode 100644 index 0000000000..6776488ce6 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/sdk.gen.ts @@ -0,0 +1,127 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Client, Options as Options2, TDataShape } from './client'; +import { client } from './client.gen'; +import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses } from './types.gen'; + +export type Options = Options2 & { + /** + * You can provide a client instance returned by `createClient()` instead of + * individual options. This might be also useful if you want to implement a + * custom client. + */ + client?: Client; + /** + * You can pass arbitrary values through the `meta` object. This can be + * used to access values that aren't defined as part of the SDK function. + */ + meta?: Record; +}; + +export const serviceWithEmptyTag = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); + +export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); + +export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); + +export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); + +export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); + +export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); + +export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); + +export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); + +export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); + +export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); + +export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions/', ...options }); + +export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); + +export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ + querySerializer: { parameters: { parameterModel: { object: { explode: false, style: 'form' } } } }, + url: '/api/v{api-version}/defaults', + ...options +}); + +export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); + +export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); + +export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); + +export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); + +export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); + +export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); + +export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); + +export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); + +export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); + +export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); + +export const collectionFormat = (options: Options) => (options.client ?? client).get({ + querySerializer: { parameters: { + parameterArrayCSV: { array: { explode: false } }, + parameterArraySSV: { array: { explode: false } }, + parameterArrayTSV: { array: { explode: false } }, + parameterArrayPipes: { array: { explode: false } } + } }, + url: '/api/v{api-version}/collectionFormat', + ...options +}); + +export const types = (options: Options) => (options.client ?? client).get({ + querySerializer: { parameters: { parameterArray: { array: { explode: false } }, parameterDictionary: { object: { explode: false, style: 'form' } } } }, + url: '/api/v{api-version}/types', + ...options +}); + +export const complexTypes = (options: Options) => (options.client ?? client).get({ + querySerializer: { parameters: { parameterObject: { object: { explode: false, style: 'form' } }, parameterReference: { object: { explode: false, style: 'form' } } } }, + url: '/api/v{api-version}/complex', + ...options +}); + +export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); + +export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); + +export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); + +/** + * Body should not be unknown + * + * Body should not be unknown + */ +export const postApiVbyApiVersionBody = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/body', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/types.gen.ts new file mode 100644 index 0000000000..d69b074040 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery-disabled/types.gen.ts @@ -0,0 +1,1190 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type ClientOptions = { + baseUrl: 'http://localhost:3000/base' | (string & {}); +}; + +export type ExternalRefA = ExternalSharedModel; + +export type ExternalRefB = ExternalSharedModel; + +/** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ +export type CommentWithBreaks = number; + +/** + * Testing backticks in string: `backticks` and ```multiple backticks``` should work + */ +export type CommentWithBackticks = number; + +/** + * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work + */ +export type CommentWithBackticksAndQuotes = number; + +/** + * Testing slashes in string: \backwards\\\ and /forwards/// should work + */ +export type CommentWithSlashes = number; + +/** + * Testing expression placeholders in string: ${expression} should work + */ +export type CommentWithExpressionPlaceholders = number; + +/** + * Testing quotes in string: 'single quote''' and "double quotes""" should work + */ +export type CommentWithQuotes = number; + +/** + * Testing reserved characters in string: * inline * and ** inline ** should work + */ +export type CommentWithReservedCharacters = number; + +/** + * This is a simple number + */ +export type SimpleInteger = number; + +/** + * This is a simple boolean + */ +export type SimpleBoolean = boolean; + +/** + * This is a simple string + */ +export type SimpleString = string; + +/** + * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) + */ +export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; + +/** + * This is a simple file + */ +export type SimpleFile = Blob | File; + +export type SimpleReference = ModelWithString; + +/** + * This is a simple string + */ +export type SimpleStringWithPattern = string; + +/** + * This is a simple enum with strings + */ +export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; + +/** + * This is a simple enum with numbers + */ +export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; + +/** + * Success=1,Warning=2,Error=3 + */ +export type EnumFromDescription = number; + +/** + * This is a simple enum with numbers + */ +export type EnumWithExtensions = 200 | 400 | 500; + +/** + * This is a simple array with numbers + */ +export type ArrayWithNumbers = Array; + +/** + * This is a simple array with booleans + */ +export type ArrayWithBooleans = Array; + +/** + * This is a simple array with strings + */ +export type ArrayWithStrings = Array; + +/** + * This is a simple array with references + */ +export type ArrayWithReferences = Array; + +/** + * This is a simple array containing an array + */ +export type ArrayWithArray = Array>; + +/** + * This is a simple array with properties + */ +export type ArrayWithProperties = Array<{ + foo?: string; + bar?: string; +}>; + +/** + * This is a string dictionary + */ +export type DictionaryWithString = { + [key: string]: string; +}; + +/** + * This is a string reference + */ +export type DictionaryWithReference = { + [key: string]: ModelWithString; +}; + +/** + * This is a complex dictionary + */ +export type DictionaryWithArray = { + [key: string]: Array; +}; + +/** + * This is a string dictionary + */ +export type DictionaryWithDictionary = { + [key: string]: { + [key: string]: string; + }; +}; + +/** + * This is a complex dictionary + */ +export type DictionaryWithProperties = { + [key: string]: { + foo?: string; + bar?: string; + }; +}; + +/** + * This is a type-only model that defines Date as a string + */ +export type Date = string; + +/** + * This is a model with one number property + */ +export type ModelWithInteger = { + /** + * This is a simple number property + */ + prop?: number; +}; + +/** + * This is a model with one boolean property + */ +export type ModelWithBoolean = { + /** + * This is a simple boolean property + */ + prop?: boolean; +}; + +/** + * This is a model with one string property + */ +export type ModelWithString = { + /** + * This is a simple string property + */ + prop?: string; +}; + +/** + * This is a model with one string property + */ +export type ModelWithStringError = { + /** + * This is a simple string property + */ + prop?: string; +}; + +/** + * This is a model with one string property + */ +export type ModelWithNullableString = { + /** + * This is a simple string property + */ + nullableProp?: string | null; + /** + * This is a simple string property + */ + nullableRequiredProp: string | null; +}; + +/** + * This is a model with one enum + */ +export type ModelWithEnum = { + /** + * This is a simple enum with strings + */ + test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; + /** + * These are the HTTP error code enums + */ + statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; + /** + * Simple boolean enum + */ + bool?: true; +}; + +/** + * This is a model with one enum + */ +export type ModelWithEnumFromDescription = { + /** + * Success=1,Warning=2,Error=3 + */ + test?: number; +}; + +/** + * This is a model with nested enums + */ +export type ModelWithNestedEnums = { + dictionaryWithEnum?: { + [key: string]: 'Success' | 'Warning' | 'Error'; + }; + dictionaryWithEnumFromDescription?: { + [key: string]: number; + }; + arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; + arrayWithDescription?: Array; +}; + +/** + * This is a model with one property containing a reference + */ +export type ModelWithReference = { + prop?: ModelWithProperties; +}; + +/** + * This is a model with one property containing an array + */ +export type ModelWithArray = { + prop?: Array; + propWithFile?: Array; + propWithNumber?: Array; +}; + +/** + * This is a model with one property containing a dictionary + */ +export type ModelWithDictionary = { + prop?: { + [key: string]: string; + }; +}; + +/** + * This is a model with one property containing a circular reference + */ +export type ModelWithCircularReference = { + prop?: ModelWithCircularReference; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithProperties = { + required: string; + readonly requiredAndReadOnly: string; + string?: string; + number?: number; + boolean?: boolean; + reference?: ModelWithString; + 'property with space'?: string; + default?: string; + try?: string; + readonly '@namespace.string'?: string; + readonly '@namespace.integer'?: number; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithNestedProperties = { + readonly first: { + readonly second: { + readonly third: string; + }; + }; +}; + +/** + * This is a model with duplicated properties + */ +export type ModelWithDuplicateProperties = { + prop?: ModelWithString; +}; + +/** + * This is a model with ordered properties + */ +export type ModelWithOrderedProperties = { + zebra?: string; + apple?: string; + hawaii?: string; +}; + +/** + * This is a model with duplicated imports + */ +export type ModelWithDuplicateImports = { + propA?: ModelWithString; + propB?: ModelWithString; + propC?: ModelWithString; +}; + +/** + * This is a model that extends another model + */ +export type ModelThatExtends = ModelWithString & { + propExtendsA?: string; + propExtendsB?: ModelWithString; +}; + +/** + * This is a model that extends another model + */ +export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { + propExtendsC?: string; + propExtendsD?: ModelWithString; +}; + +export type Default = { + name?: string; +}; + +/** + * This is a model that contains a some patterns + */ +export type ModelWithPattern = { + key: string; + name: string; + readonly enabled?: boolean; + readonly modified?: string; + id?: string; + text?: string; + patternWithSingleQuotes?: string; + patternWithNewline?: string; + patternWithBacktick?: string; + patternWithUnicode?: string; +}; + +export type ParameterActivityParams = { + description?: string; + graduate_id?: number; + organization_id?: number; + parent_activity?: number; + post_id?: number; +}; + +export type ResponsePostActivityResponse = { + description?: string; + graduate_id?: number; + organization_id?: number; + parent_activity_id?: number; + post_id?: number; +}; + +export type FailureFailure = { + error?: string; + message?: string; + reference_code?: string; +}; + +export type ExternalSharedModel = { + id: string; + name?: string; +}; + +/** + * This is a model with one property containing a reference + */ +export type ModelWithReferenceWritable = { + prop?: ModelWithPropertiesWritable; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithPropertiesWritable = { + required: string; + string?: string; + number?: number; + boolean?: boolean; + reference?: ModelWithString; + 'property with space'?: string; + default?: string; + try?: string; +}; + +/** + * This is a model that contains a some patterns + */ +export type ModelWithPatternWritable = { + key: string; + name: string; + id?: string; + text?: string; + patternWithSingleQuotes?: string; + patternWithNewline?: string; + patternWithBacktick?: string; + patternWithUnicode?: string; +}; + +export type ServiceWithEmptyTagData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type PatchApiVbyApiVersionNoTagData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type PatchApiVbyApiVersionNoTagResponses = { + /** + * OK + */ + default: unknown; +}; + +export type FooWowData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type FooWowResponses = { + /** + * OK + */ + default: unknown; +}; + +export type DeleteCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type GetCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type HeadCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type OptionsCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PatchCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PostCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PutCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type CallWithDescriptionsData = { + body?: never; + path?: never; + query?: { + /** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ + parameterWithBreaks?: string; + /** + * Testing backticks in string: `backticks` and ```multiple backticks``` should work + */ + parameterWithBackticks?: string; + /** + * Testing slashes in string: \backwards\\\ and /forwards/// should work + */ + parameterWithSlashes?: string; + /** + * Testing expression placeholders in string: ${expression} should work + */ + parameterWithExpressionPlaceholders?: string; + /** + * Testing quotes in string: 'single quote''' and "double quotes""" should work + */ + parameterWithQuotes?: string; + /** + * Testing reserved characters in string: * inline * and ** inline ** should work + */ + parameterWithReservedCharacters?: string; + }; + url: '/api/v{api-version}/descriptions/'; +}; + +export type CallWithParametersData = { + body?: never; + headers: { + /** + * This is the parameter that goes into the header + */ + parameterHeader: string; + }; + path: { + /** + * This is the parameter that goes into the path + */ + parameterPath: string; + /** + * api-version should be required in standalone clients + */ + 'api-version': string; + }; + query: { + /** + * This is the parameter that goes into the query params + */ + parameterQuery: string; + }; + url: '/api/v{api-version}/parameters/{parameterPath}'; +}; + +export type CallWithWeirdParameterNamesData = { + /** + * This is the parameter that is sent as request body + */ + body: string; + headers: { + /** + * This is the parameter that goes into the request header + */ + 'parameter.header': string; + }; + path: { + /** + * This is the parameter that goes into the path + */ + 'parameter.path.1'?: string; + /** + * This is the parameter that goes into the path + */ + 'parameter-path-2'?: string; + /** + * This is the parameter that goes into the path + */ + 'PARAMETER-PATH-3'?: string; + /** + * api-version should be required in standalone clients + */ + 'api-version': string; + }; + query: { + /** + * This is the parameter with a reserved keyword + */ + default?: string; + /** + * This is the parameter that goes into the request query params + */ + 'parameter-query': string; + }; + url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; +}; + +export type CallWithDefaultParametersData = { + body?: never; + path?: never; + query: { + /** + * This is a simple string with default value + */ + parameterString: string; + /** + * This is a simple number with default value + */ + parameterNumber: number; + /** + * This is a simple boolean with default value + */ + parameterBoolean: boolean; + /** + * This is a simple enum with default value + */ + parameterEnum: 'Success' | 'Warning' | 'Error'; + /** + * This is a model with one string property + */ + parameterModel: { + /** + * This is a simple string property + */ + prop?: string; + }; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type CallWithDefaultOptionalParametersData = { + body?: never; + path?: never; + query?: { + /** + * This is a simple string that is optional with default value + */ + parameterString?: string; + /** + * This is a simple number that is optional with default value + */ + parameterNumber?: number; + /** + * This is a simple boolean that is optional with default value + */ + parameterBoolean?: boolean; + /** + * This is a simple enum that is optional with default value + */ + parameterEnum?: 'Success' | 'Warning' | 'Error'; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type CallToTestOrderOfParamsData = { + body?: never; + path?: never; + query: { + /** + * This is a optional string with default + */ + parameterOptionalStringWithDefault?: string; + /** + * This is a optional string with empty default + */ + parameterOptionalStringWithEmptyDefault?: string; + /** + * This is a optional string with no default + */ + parameterOptionalStringWithNoDefault?: string; + /** + * This is a string with default + */ + parameterStringWithDefault: string; + /** + * This is a string with empty default + */ + parameterStringWithEmptyDefault: string; + /** + * This is a string with no default + */ + parameterStringWithNoDefault: string; + /** + * This is a string that can be null with no default + */ + parameterStringNullableWithNoDefault?: string | null; + /** + * This is a string that can be null with default + */ + parameterStringNullableWithDefault?: string | null; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type DuplicateNameData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName2Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName3Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName4Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type CallWithNoContentResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no-content'; +}; + +export type CallWithNoContentResponseResponses = { + /** + * Success + */ + 204: unknown; +}; + +export type CallWithResponseAndNoContentResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/response-and-no-content'; +}; + +export type CallWithResponseAndNoContentResponseResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Success + */ + 204: unknown; +}; + +export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; + +export type DummyAData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/a'; +}; + +export type DummyAResponses = { + /** + * Success + */ + 204: unknown; +}; + +export type DummyBData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/b'; +}; + +export type DummyBResponses = { + /** + * Success + */ + 204: unknown; +}; + +export type CallWithResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithResponseResponses = { + /** + * Message for default response + */ + default: ModelWithString; +}; + +export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; + +export type CallWithDuplicateResponsesData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithDuplicateResponsesErrors = { + /** + * Message for 500 error + */ + 500: ModelWithStringError; + /** + * Message for 501 error + */ + 501: ModelWithStringError; + /** + * Message for 502 error + */ + 502: ModelWithStringError; + /** + * Message for default response + */ + default: ModelWithString; +}; + +export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; + +export type CallWithDuplicateResponsesResponses = { + /** + * Message for 201 response + */ + 201: ModelWithString; + /** + * Message for 202 response + */ + 202: ModelWithString; +}; + +export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; + +export type CallWithResponsesData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithResponsesErrors = { + /** + * Message for 500 error + */ + 500: ModelWithStringError; + /** + * Message for 501 error + */ + 501: ModelWithStringError; + /** + * Message for 502 error + */ + 502: ModelWithStringError; + /** + * Message for default response + */ + default: ModelWithString; +}; + +export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; + +export type CallWithResponsesResponses = { + /** + * Message for 200 response + */ + 200: { + readonly '@namespace.string'?: string; + readonly '@namespace.integer'?: number; + readonly value?: Array; + }; + /** + * Message for 201 response + */ + 201: ModelThatExtends; + /** + * Message for 202 response + */ + 202: ModelThatExtendsExtends; +}; + +export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; + +export type CollectionFormatData = { + body?: never; + path?: never; + query: { + /** + * This is an array parameter that is sent as csv format (comma-separated values) + */ + parameterArrayCSV: Array; + /** + * This is an array parameter that is sent as ssv format (space-separated values) + */ + parameterArraySSV: Array; + /** + * This is an array parameter that is sent as tsv format (tab-separated values) + */ + parameterArrayTSV: Array; + /** + * This is an array parameter that is sent as pipes format (pipe-separated values) + */ + parameterArrayPipes: Array; + /** + * This is an array parameter that is sent as multi format (multiple parameter instances) + */ + parameterArrayMulti: Array; + }; + url: '/api/v{api-version}/collectionFormat'; +}; + +export type TypesData = { + body?: never; + path?: { + /** + * This is a number parameter + */ + id?: number; + }; + query: { + /** + * This is a number parameter + */ + parameterNumber: number; + /** + * This is a string parameter + */ + parameterString: string; + /** + * This is a boolean parameter + */ + parameterBoolean: boolean; + /** + * This is an array parameter + */ + parameterArray: Array; + /** + * This is a dictionary parameter + */ + parameterDictionary: { + [key: string]: unknown; + }; + /** + * This is an enum parameter + */ + parameterEnum: 'Success' | 'Warning' | 'Error'; + }; + url: '/api/v{api-version}/types'; +}; + +export type TypesResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Response is a simple string + */ + 201: string; + /** + * Response is a simple boolean + */ + 202: boolean; + /** + * Response is a simple object + */ + 203: { + [key: string]: unknown; + }; +}; + +export type TypesResponse = TypesResponses[keyof TypesResponses]; + +export type ComplexTypesData = { + body?: never; + path?: never; + query: { + /** + * Parameter containing object + */ + parameterObject: { + first?: { + second?: { + third?: string; + }; + }; + }; + /** + * This is a model with one string property + */ + parameterReference: { + /** + * This is a simple string property + */ + prop?: string; + }; + }; + url: '/api/v{api-version}/complex'; +}; + +export type ComplexTypesErrors = { + /** + * 400 server error + */ + 400: unknown; + /** + * 500 server error + */ + 500: unknown; +}; + +export type ComplexTypesResponses = { + /** + * Successful response + */ + 200: Array; +}; + +export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; + +export type CallWithResultFromHeaderData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/header'; +}; + +export type CallWithResultFromHeaderErrors = { + /** + * 400 server error + */ + 400: unknown; + /** + * 500 server error + */ + 500: unknown; +}; + +export type CallWithResultFromHeaderResponses = { + /** + * Successful response + */ + 200: unknown; +}; + +export type TestErrorCodeData = { + body?: never; + path?: never; + query: { + /** + * Status code to return + */ + status: string; + }; + url: '/api/v{api-version}/error'; +}; + +export type TestErrorCodeErrors = { + /** + * Custom message: Internal Server Error + */ + 500: unknown; + /** + * Custom message: Not Implemented + */ + 501: unknown; + /** + * Custom message: Bad Gateway + */ + 502: unknown; + /** + * Custom message: Service Unavailable + */ + 503: unknown; +}; + +export type TestErrorCodeResponses = { + /** + * Custom message: Successful response + */ + 200: unknown; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Data = { + body?: never; + path?: never; + query: { + /** + * Dummy input param + */ + nonAsciiParamæøåÆØÅöôêÊ: number; + }; + url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { + /** + * Successful response + */ + 200: NonAsciiStringæøåÆøÅöôêÊ字符串; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; + +export type PostApiVbyApiVersionBodyData = { + /** + * Body should not be unknown + */ + body: ParameterActivityParams; + path?: never; + query?: never; + url: '/api/v{api-version}/body'; +}; + +export type PostApiVbyApiVersionBodyErrors = { + /** + * Bad Request + */ + 400: FailureFailure; + /** + * Internal Server Error + */ + 500: FailureFailure; +}; + +export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; + +export type PostApiVbyApiVersionBodyResponses = { + /** + * OK + */ + 200: ResponsePostActivityResponse; +}; + +export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/@tanstack/react-query.gen.ts new file mode 100644 index 0000000000..f07d7c3cd9 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/@tanstack/react-query.gen.ts @@ -0,0 +1,565 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/react-query'; + +import { client } from '../client.gen'; +import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; +import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyBData, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, GetCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TypesData, TypesResponse } from '../types.gen'; + +export type QueryKey = [ + Pick & { + _id: string; + _infinite?: boolean; + tags?: ReadonlyArray; + } +]; + +const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ + QueryKey[0] +] => { + const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; + if (infinite) { + params._infinite = infinite; + } + if (tags) { + params.tags = tags; + } + if (options?.body) { + params.body = options.body; + } + if (options?.headers) { + params.headers = options.headers; + } + if (options?.path) { + params.path = options.path; + } + if (options?.query) { + params.query = options.query; + } + return [params]; +}; + +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + +export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); + +export const serviceWithEmptyTagOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await serviceWithEmptyTag({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: serviceWithEmptyTagQueryKey(resolveOptions(options)) +}); + +const queryWithOptions = (optionsFn: Function, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useServiceWithEmptyTagQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(serviceWithEmptyTagOptions, options); + +export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await patchApiVbyApiVersionNoTag({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const fooWowMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await fooWow({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deleteCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); + +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await getCallWithoutParametersAndResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: getCallWithoutParametersAndResponseQueryKey(resolveOptions(options)) +}); + +export const useGetCallWithoutParametersAndResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithoutParametersAndResponseOptions, options); + +export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await patchCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await putCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDescriptions({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithParametersMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithParameters({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithWeirdParameterNames({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithDefaultParametersQueryKey = (options: Options) => createQueryKey('callWithDefaultParameters', options); + +export const callWithDefaultParametersOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithDefaultParameters({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithDefaultParametersQueryKey(resolveOptions(options)) +}); + +export const useCallWithDefaultParametersQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithDefaultParametersOptions, options); + +export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDefaultOptionalParameters({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callToTestOrderOfParams({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateNameMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); + +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await duplicateName2({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) +}); + +export const useDuplicateName2Query = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(duplicateName2Options, options); + +export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName3({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName4({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); + +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithNoContentResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithNoContentResponseQueryKey(resolveOptions(options)) +}); + +export const useCallWithNoContentResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithNoContentResponseOptions, options); + +export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); + +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithResponseAndNoContentResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithResponseAndNoContentResponseQueryKey(resolveOptions(options)) +}); + +export const useCallWithResponseAndNoContentResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseAndNoContentResponseOptions, options); + +export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); + +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await dummyA({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: dummyAQueryKey(resolveOptions(options)) +}); + +export const useDummyAQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyAOptions, options); + +export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); + +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await dummyB({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: dummyBQueryKey(resolveOptions(options)) +}); + +export const useDummyBQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyBOptions, options); + +export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); + +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) +}); + +export const useCallWithResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseOptions, options); + +export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDuplicateResponses({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithResponses({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); + +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await collectionFormat({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) +}); + +export const useCollectionFormatQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(collectionFormatOptions, options); + +export const typesQueryKey = (options: Options) => createQueryKey('types', options); + +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await types({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: typesQueryKey(resolveOptions(options)) +}); + +export const useTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(typesOptions, options); + +export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); + +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await complexTypes({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) +}); + +export const useComplexTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(complexTypesOptions, options); + +export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithResultFromHeader({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await testErrorCode({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * Body should not be unknown + * + * Body should not be unknown + */ +export const postApiVbyApiVersionBodyMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postApiVbyApiVersionBody({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/client.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/client.gen.ts new file mode 100644 index 0000000000..25cd14eafb --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/client.gen.ts @@ -0,0 +1,16 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type ClientOptions, type Config, createClient, createConfig } from './client'; +import type { ClientOptions as ClientOptions2 } from './types.gen'; + +/** + * The `createClientConfig()` function will be called on client initialization + * and the returned object will become the client's initial configuration. + * + * You may want to initialize your client this way instead of calling + * `setConfig()`. This is useful for example if you're using Next.js + * to ensure your client always has the correct values. + */ +export type CreateClientConfig = (override?: Config) => Config & T>; + +export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/client/client.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/client/client.gen.ts new file mode 100644 index 0000000000..14dc0a0ec5 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/client/client.gen.ts @@ -0,0 +1,290 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { createSseClient } from '../core/serverSentEvents.gen'; +import type { HttpMethod } from '../core/types.gen'; +import { getValidRequestBody } from '../core/utils.gen'; +import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; +import { + buildUrl, + createConfig, + createInterceptors, + getParseAs, + mergeConfigs, + mergeHeaders, + setAuthParams, +} from './utils.gen'; + +type ReqInit = Omit & { + body?: any; + headers: ReturnType; +}; + +export const createClient = (config: Config = {}): Client => { + let _config = mergeConfigs(createConfig(), config); + + const getConfig = (): Config => ({ ..._config }); + + const setConfig = (config: Config): Config => { + _config = mergeConfigs(_config, config); + return getConfig(); + }; + + const interceptors = createInterceptors(); + + const beforeRequest = async (options: RequestOptions) => { + const opts = { + ..._config, + ...options, + fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, + headers: mergeHeaders(_config.headers, options.headers), + serializedBody: undefined as string | undefined, + }; + + if (opts.security) { + await setAuthParams({ + ...opts, + security: opts.security, + }); + } + + if (opts.requestValidator) { + await opts.requestValidator(opts); + } + + if (opts.body !== undefined && opts.bodySerializer) { + opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; + } + + // remove Content-Type header if body is empty to avoid sending invalid requests + if (opts.body === undefined || opts.serializedBody === '') { + opts.headers.delete('Content-Type'); + } + + const url = buildUrl(opts); + + return { opts, url }; + }; + + const request: Client['request'] = async (options) => { + // @ts-expect-error + const { opts, url } = await beforeRequest(options); + const requestInit: ReqInit = { + redirect: 'follow', + ...opts, + body: getValidRequestBody(opts), + }; + + let request = new Request(url, requestInit); + + for (const fn of interceptors.request.fns) { + if (fn) { + request = await fn(request, opts); + } + } + + // fetch must be assigned here, otherwise it would throw the error: + // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation + const _fetch = opts.fetch!; + let response: Response; + + try { + response = await _fetch(request); + } catch (error) { + // Handle fetch exceptions (AbortError, network errors, etc.) + let finalError = error; + + for (const fn of interceptors.error.fns) { + if (fn) { + finalError = (await fn(error, undefined as any, request, opts)) as unknown; + } + } + + finalError = finalError || ({} as unknown); + + if (opts.throwOnError) { + throw finalError; + } + + // Return error response + return opts.responseStyle === 'data' + ? undefined + : { + error: finalError, + request, + response: undefined as any, + }; + } + + for (const fn of interceptors.response.fns) { + if (fn) { + response = await fn(response, request, opts); + } + } + + const result = { + request, + response, + }; + + if (response.ok) { + const parseAs = + (opts.parseAs === 'auto' + ? getParseAs(response.headers.get('Content-Type')) + : opts.parseAs) ?? 'json'; + + if (response.status === 204 || response.headers.get('Content-Length') === '0') { + let emptyData: any; + switch (parseAs) { + case 'arrayBuffer': + case 'blob': + case 'text': + emptyData = await response[parseAs](); + break; + case 'formData': + emptyData = new FormData(); + break; + case 'stream': + emptyData = response.body; + break; + case 'json': + default: + emptyData = {}; + break; + } + return opts.responseStyle === 'data' + ? emptyData + : { + data: emptyData, + ...result, + }; + } + + let data: any; + switch (parseAs) { + case 'arrayBuffer': + case 'blob': + case 'formData': + case 'text': + data = await response[parseAs](); + break; + case 'json': { + // Some servers return 200 with no Content-Length and empty body. + // response.json() would throw; read as text and parse if non-empty. + const text = await response.text(); + data = text ? JSON.parse(text) : {}; + break; + } + case 'stream': + return opts.responseStyle === 'data' + ? response.body + : { + data: response.body, + ...result, + }; + } + + if (parseAs === 'json') { + if (opts.responseValidator) { + await opts.responseValidator(data); + } + + if (opts.responseTransformer) { + data = await opts.responseTransformer(data); + } + } + + return opts.responseStyle === 'data' + ? data + : { + data, + ...result, + }; + } + + const textError = await response.text(); + let jsonError: unknown; + + try { + jsonError = JSON.parse(textError); + } catch { + // noop + } + + const error = jsonError ?? textError; + let finalError = error; + + for (const fn of interceptors.error.fns) { + if (fn) { + finalError = (await fn(error, response, request, opts)) as string; + } + } + + finalError = finalError || ({} as string); + + if (opts.throwOnError) { + throw finalError; + } + + // TODO: we probably want to return error and improve types + return opts.responseStyle === 'data' + ? undefined + : { + error: finalError, + ...result, + }; + }; + + const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => + request({ ...options, method }); + + const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { + const { opts, url } = await beforeRequest(options); + return createSseClient({ + ...opts, + body: opts.body as BodyInit | null | undefined, + headers: opts.headers as unknown as Record, + method, + onRequest: async (url, init) => { + let request = new Request(url, init); + for (const fn of interceptors.request.fns) { + if (fn) { + request = await fn(request, opts); + } + } + return request; + }, + serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, + url, + }); + }; + + const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); + + return { + buildUrl: _buildUrl, + connect: makeMethodFn('CONNECT'), + delete: makeMethodFn('DELETE'), + get: makeMethodFn('GET'), + getConfig, + head: makeMethodFn('HEAD'), + interceptors, + options: makeMethodFn('OPTIONS'), + patch: makeMethodFn('PATCH'), + post: makeMethodFn('POST'), + put: makeMethodFn('PUT'), + request, + setConfig, + sse: { + connect: makeSseFn('CONNECT'), + delete: makeSseFn('DELETE'), + get: makeSseFn('GET'), + head: makeSseFn('HEAD'), + options: makeSseFn('OPTIONS'), + patch: makeSseFn('PATCH'), + post: makeSseFn('POST'), + put: makeSseFn('PUT'), + trace: makeSseFn('TRACE'), + }, + trace: makeMethodFn('TRACE'), + } as Client; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/client/index.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/client/index.ts new file mode 100644 index 0000000000..b295edeca0 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/client/index.ts @@ -0,0 +1,25 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type { Auth } from '../core/auth.gen'; +export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; +export { + formDataBodySerializer, + jsonBodySerializer, + urlSearchParamsBodySerializer, +} from '../core/bodySerializer.gen'; +export { buildClientParams } from '../core/params.gen'; +export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; +export { createClient } from './client.gen'; +export type { + Client, + ClientOptions, + Config, + CreateClientConfig, + Options, + RequestOptions, + RequestResult, + ResolvedRequestOptions, + ResponseStyle, + TDataShape, +} from './types.gen'; +export { createConfig, mergeHeaders } from './utils.gen'; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/client/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/client/types.gen.ts new file mode 100644 index 0000000000..a3f8616511 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/client/types.gen.ts @@ -0,0 +1,214 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Auth } from '../core/auth.gen'; +import type { + ServerSentEventsOptions, + ServerSentEventsResult, +} from '../core/serverSentEvents.gen'; +import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; +import type { Middleware } from './utils.gen'; + +export type ResponseStyle = 'data' | 'fields'; + +export interface Config + extends Omit, CoreConfig { + /** + * Base URL for all requests made by this client. + */ + baseUrl?: T['baseUrl']; + /** + * Fetch API implementation. You can use this option to provide a custom + * fetch instance. + * + * @default globalThis.fetch + */ + fetch?: typeof fetch; + /** + * Please don't use the Fetch client for Next.js applications. The `next` + * options won't have any effect. + * + * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. + */ + next?: never; + /** + * Return the response data parsed in a specified format. By default, `auto` + * will infer the appropriate method from the `Content-Type` response header. + * You can override this behavior with any of the {@link Body} methods. + * Select `stream` if you don't want to parse response data at all. + * + * @default 'auto' + */ + parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; + /** + * Should we return only data or multiple fields (data, error, response, etc.)? + * + * @default 'fields' + */ + responseStyle?: ResponseStyle; + /** + * Throw an error instead of returning it in the response? + * + * @default false + */ + throwOnError?: T['throwOnError']; +} + +export interface RequestOptions< + TData = unknown, + TResponseStyle extends ResponseStyle = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, +> + extends + Config<{ + responseStyle: TResponseStyle; + throwOnError: ThrowOnError; + }>, + Pick< + ServerSentEventsOptions, + | 'onRequest' + | 'onSseError' + | 'onSseEvent' + | 'sseDefaultRetryDelay' + | 'sseMaxRetryAttempts' + | 'sseMaxRetryDelay' + > { + /** + * Any body that you want to add to your request. + * + * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} + */ + body?: unknown; + path?: Record; + query?: Record; + /** + * Security mechanism(s) to use for the request. + */ + security?: ReadonlyArray; + url: Url; +} + +export interface ResolvedRequestOptions< + TResponseStyle extends ResponseStyle = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, +> extends RequestOptions { + serializedBody?: string; +} + +export type RequestResult< + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = boolean, + TResponseStyle extends ResponseStyle = 'fields', +> = ThrowOnError extends true + ? Promise< + TResponseStyle extends 'data' + ? TData extends Record + ? TData[keyof TData] + : TData + : { + data: TData extends Record ? TData[keyof TData] : TData; + request: Request; + response: Response; + } + > + : Promise< + TResponseStyle extends 'data' + ? (TData extends Record ? TData[keyof TData] : TData) | undefined + : ( + | { + data: TData extends Record ? TData[keyof TData] : TData; + error: undefined; + } + | { + data: undefined; + error: TError extends Record ? TError[keyof TError] : TError; + } + ) & { + request: Request; + response: Response; + } + >; + +export interface ClientOptions { + baseUrl?: string; + responseStyle?: ResponseStyle; + throwOnError?: boolean; +} + +type MethodFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'>, +) => RequestResult; + +type SseFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'>, +) => Promise>; + +type RequestFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'> & + Pick>, 'method'>, +) => RequestResult; + +type BuildUrlFn = < + TData extends { + body?: unknown; + path?: Record; + query?: Record; + url: string; + }, +>( + options: TData & Options, +) => string; + +export type Client = CoreClient & { + interceptors: Middleware; +}; + +/** + * The `createClientConfig()` function will be called on client initialization + * and the returned object will become the client's initial configuration. + * + * You may want to initialize your client this way instead of calling + * `setConfig()`. This is useful for example if you're using Next.js + * to ensure your client always has the correct values. + */ +export type CreateClientConfig = ( + override?: Config, +) => Config & T>; + +export interface TDataShape { + body?: unknown; + headers?: unknown; + path?: unknown; + query?: unknown; + url: string; +} + +type OmitKeys = Pick>; + +export type Options< + TData extends TDataShape = TDataShape, + ThrowOnError extends boolean = boolean, + TResponse = unknown, + TResponseStyle extends ResponseStyle = 'fields', +> = OmitKeys< + RequestOptions, + 'body' | 'path' | 'query' | 'url' +> & + ([TData] extends [never] ? unknown : Omit); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/client/utils.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/client/utils.gen.ts new file mode 100644 index 0000000000..b4bd2435ce --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/client/utils.gen.ts @@ -0,0 +1,316 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { getAuthToken } from '../core/auth.gen'; +import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; +import { jsonBodySerializer } from '../core/bodySerializer.gen'; +import { + serializeArrayParam, + serializeObjectParam, + serializePrimitiveParam, +} from '../core/pathSerializer.gen'; +import { getUrl } from '../core/utils.gen'; +import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; + +export const createQuerySerializer = ({ + parameters = {}, + ...args +}: QuerySerializerOptions = {}) => { + const querySerializer = (queryParams: T) => { + const search: string[] = []; + if (queryParams && typeof queryParams === 'object') { + for (const name in queryParams) { + const value = queryParams[name]; + + if (value === undefined || value === null) { + continue; + } + + const options = parameters[name] || args; + + if (Array.isArray(value)) { + const serializedArray = serializeArrayParam({ + allowReserved: options.allowReserved, + explode: true, + name, + style: 'form', + value, + ...options.array, + }); + if (serializedArray) search.push(serializedArray); + } else if (typeof value === 'object') { + const serializedObject = serializeObjectParam({ + allowReserved: options.allowReserved, + explode: true, + name, + style: 'deepObject', + value: value as Record, + ...options.object, + }); + if (serializedObject) search.push(serializedObject); + } else { + const serializedPrimitive = serializePrimitiveParam({ + allowReserved: options.allowReserved, + name, + value: value as string, + }); + if (serializedPrimitive) search.push(serializedPrimitive); + } + } + } + return search.join('&'); + }; + return querySerializer; +}; + +/** + * Infers parseAs value from provided Content-Type header. + */ +export const getParseAs = (contentType: string | null): Exclude => { + if (!contentType) { + // If no Content-Type header is provided, the best we can do is return the raw response body, + // which is effectively the same as the 'stream' option. + return 'stream'; + } + + const cleanContent = contentType.split(';')[0]?.trim(); + + if (!cleanContent) { + return; + } + + if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { + return 'json'; + } + + if (cleanContent === 'multipart/form-data') { + return 'formData'; + } + + if ( + ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) + ) { + return 'blob'; + } + + if (cleanContent.startsWith('text/')) { + return 'text'; + } + + return; +}; + +const checkForExistence = ( + options: Pick & { + headers: Headers; + }, + name?: string, +): boolean => { + if (!name) { + return false; + } + if ( + options.headers.has(name) || + options.query?.[name] || + options.headers.get('Cookie')?.includes(`${name}=`) + ) { + return true; + } + return false; +}; + +export const setAuthParams = async ({ + security, + ...options +}: Pick, 'security'> & + Pick & { + headers: Headers; + }) => { + for (const auth of security) { + if (checkForExistence(options, auth.name)) { + continue; + } + + const token = await getAuthToken(auth, options.auth); + + if (!token) { + continue; + } + + const name = auth.name ?? 'Authorization'; + + switch (auth.in) { + case 'query': + if (!options.query) { + options.query = {}; + } + options.query[name] = token; + break; + case 'cookie': + options.headers.append('Cookie', `${name}=${token}`); + break; + case 'header': + default: + options.headers.set(name, token); + break; + } + } +}; + +export const buildUrl: Client['buildUrl'] = (options) => + getUrl({ + baseUrl: options.baseUrl as string, + path: options.path, + query: options.query, + querySerializer: + typeof options.querySerializer === 'function' + ? options.querySerializer + : createQuerySerializer(options.querySerializer), + url: options.url, + }); + +export const mergeConfigs = (a: Config, b: Config): Config => { + const config = { ...a, ...b }; + if (config.baseUrl?.endsWith('/')) { + config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); + } + config.headers = mergeHeaders(a.headers, b.headers); + return config; +}; + +const headersEntries = (headers: Headers): Array<[string, string]> => { + const entries: Array<[string, string]> = []; + headers.forEach((value, key) => { + entries.push([key, value]); + }); + return entries; +}; + +export const mergeHeaders = ( + ...headers: Array['headers'] | undefined> +): Headers => { + const mergedHeaders = new Headers(); + for (const header of headers) { + if (!header) { + continue; + } + + const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); + + for (const [key, value] of iterator) { + if (value === null) { + mergedHeaders.delete(key); + } else if (Array.isArray(value)) { + for (const v of value) { + mergedHeaders.append(key, v as string); + } + } else if (value !== undefined) { + // assume object headers are meant to be JSON stringified, i.e. their + // content value in OpenAPI specification is 'application/json' + mergedHeaders.set( + key, + typeof value === 'object' ? JSON.stringify(value) : (value as string), + ); + } + } + } + return mergedHeaders; +}; + +type ErrInterceptor = ( + error: Err, + response: Res, + request: Req, + options: Options, +) => Err | Promise; + +type ReqInterceptor = (request: Req, options: Options) => Req | Promise; + +type ResInterceptor = ( + response: Res, + request: Req, + options: Options, +) => Res | Promise; + +class Interceptors { + fns: Array = []; + + clear(): void { + this.fns = []; + } + + eject(id: number | Interceptor): void { + const index = this.getInterceptorIndex(id); + if (this.fns[index]) { + this.fns[index] = null; + } + } + + exists(id: number | Interceptor): boolean { + const index = this.getInterceptorIndex(id); + return Boolean(this.fns[index]); + } + + getInterceptorIndex(id: number | Interceptor): number { + if (typeof id === 'number') { + return this.fns[id] ? id : -1; + } + return this.fns.indexOf(id); + } + + update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { + const index = this.getInterceptorIndex(id); + if (this.fns[index]) { + this.fns[index] = fn; + return id; + } + return false; + } + + use(fn: Interceptor): number { + this.fns.push(fn); + return this.fns.length - 1; + } +} + +export interface Middleware { + error: Interceptors>; + request: Interceptors>; + response: Interceptors>; +} + +export const createInterceptors = (): Middleware< + Req, + Res, + Err, + Options +> => ({ + error: new Interceptors>(), + request: new Interceptors>(), + response: new Interceptors>(), +}); + +const defaultQuerySerializer = createQuerySerializer({ + allowReserved: false, + array: { + explode: true, + style: 'form', + }, + object: { + explode: true, + style: 'deepObject', + }, +}); + +const defaultHeaders = { + 'Content-Type': 'application/json', +}; + +export const createConfig = ( + override: Config & T> = {}, +): Config & T> => ({ + ...jsonBodySerializer, + headers: defaultHeaders, + parseAs: 'auto', + querySerializer: defaultQuerySerializer, + ...override, +}); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/auth.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/auth.gen.ts new file mode 100644 index 0000000000..3ebf994788 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/auth.gen.ts @@ -0,0 +1,41 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type AuthToken = string | undefined; + +export interface Auth { + /** + * Which part of the request do we use to send the auth? + * + * @default 'header' + */ + in?: 'header' | 'query' | 'cookie'; + /** + * Header or query parameter name. + * + * @default 'Authorization' + */ + name?: string; + scheme?: 'basic' | 'bearer'; + type: 'apiKey' | 'http'; +} + +export const getAuthToken = async ( + auth: Auth, + callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, +): Promise => { + const token = typeof callback === 'function' ? await callback(auth) : callback; + + if (!token) { + return; + } + + if (auth.scheme === 'bearer') { + return `Bearer ${token}`; + } + + if (auth.scheme === 'basic') { + return `Basic ${btoa(token)}`; + } + + return token; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/bodySerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/bodySerializer.gen.ts new file mode 100644 index 0000000000..67daca60f8 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/bodySerializer.gen.ts @@ -0,0 +1,82 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; + +export type QuerySerializer = (query: Record) => string; + +export type BodySerializer = (body: unknown) => unknown; + +type QuerySerializerOptionsObject = { + allowReserved?: boolean; + array?: Partial>; + object?: Partial>; +}; + +export type QuerySerializerOptions = QuerySerializerOptionsObject & { + /** + * Per-parameter serialization overrides. When provided, these settings + * override the global array/object settings for specific parameter names. + */ + parameters?: Record; +}; + +const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { + if (typeof value === 'string' || value instanceof Blob) { + data.append(key, value); + } else if (value instanceof Date) { + data.append(key, value.toISOString()); + } else { + data.append(key, JSON.stringify(value)); + } +}; + +const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { + if (typeof value === 'string') { + data.append(key, value); + } else { + data.append(key, JSON.stringify(value)); + } +}; + +export const formDataBodySerializer = { + bodySerializer: (body: unknown): FormData => { + const data = new FormData(); + + Object.entries(body as Record).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + if (Array.isArray(value)) { + value.forEach((v) => serializeFormDataPair(data, key, v)); + } else { + serializeFormDataPair(data, key, value); + } + }); + + return data; + }, +}; + +export const jsonBodySerializer = { + bodySerializer: (body: unknown): string => + JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), +}; + +export const urlSearchParamsBodySerializer = { + bodySerializer: (body: unknown): string => { + const data = new URLSearchParams(); + + Object.entries(body as Record).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + if (Array.isArray(value)) { + value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); + } else { + serializeUrlSearchParamsPair(data, key, value); + } + }); + + return data.toString(); + }, +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/params.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/params.gen.ts new file mode 100644 index 0000000000..7955601a5c --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/params.gen.ts @@ -0,0 +1,169 @@ +// This file is auto-generated by @hey-api/openapi-ts + +type Slot = 'body' | 'headers' | 'path' | 'query'; + +export type Field = + | { + in: Exclude; + /** + * Field name. This is the name we want the user to see and use. + */ + key: string; + /** + * Field mapped name. This is the name we want to use in the request. + * If omitted, we use the same value as `key`. + */ + map?: string; + } + | { + in: Extract; + /** + * Key isn't required for bodies. + */ + key?: string; + map?: string; + } + | { + /** + * Field name. This is the name we want the user to see and use. + */ + key: string; + /** + * Field mapped name. This is the name we want to use in the request. + * If `in` is omitted, `map` aliases `key` to the transport layer. + */ + map: Slot; + }; + +export interface Fields { + allowExtra?: Partial>; + args?: ReadonlyArray; +} + +export type FieldsConfig = ReadonlyArray; + +const extraPrefixesMap: Record = { + $body_: 'body', + $headers_: 'headers', + $path_: 'path', + $query_: 'query', +}; +const extraPrefixes = Object.entries(extraPrefixesMap); + +type KeyMap = Map< + string, + | { + in: Slot; + map?: string; + } + | { + in?: never; + map: Slot; + } +>; + +const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { + if (!map) { + map = new Map(); + } + + for (const config of fields) { + if ('in' in config) { + if (config.key) { + map.set(config.key, { + in: config.in, + map: config.map, + }); + } + } else if ('key' in config) { + map.set(config.key, { + map: config.map, + }); + } else if (config.args) { + buildKeyMap(config.args, map); + } + } + + return map; +}; + +interface Params { + body: unknown; + headers: Record; + path: Record; + query: Record; +} + +const stripEmptySlots = (params: Params) => { + for (const [slot, value] of Object.entries(params)) { + if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { + delete params[slot as Slot]; + } + } +}; + +export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { + const params: Params = { + body: {}, + headers: {}, + path: {}, + query: {}, + }; + + const map = buildKeyMap(fields); + + let config: FieldsConfig[number] | undefined; + + for (const [index, arg] of args.entries()) { + if (fields[index]) { + config = fields[index]; + } + + if (!config) { + continue; + } + + if ('in' in config) { + if (config.key) { + const field = map.get(config.key)!; + const name = field.map || config.key; + if (field.in) { + (params[field.in] as Record)[name] = arg; + } + } else { + params.body = arg; + } + } else { + for (const [key, value] of Object.entries(arg ?? {})) { + const field = map.get(key); + + if (field) { + if (field.in) { + const name = field.map || key; + (params[field.in] as Record)[name] = value; + } else { + params[field.map] = value; + } + } else { + const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); + + if (extra) { + const [prefix, slot] = extra; + (params[slot] as Record)[key.slice(prefix.length)] = value; + } else if ('allowExtra' in config && config.allowExtra) { + for (const [slot, allowed] of Object.entries(config.allowExtra)) { + if (allowed) { + (params[slot as Slot] as Record)[key] = value; + break; + } + } + } + } + } + } + } + + stripEmptySlots(params); + + return params; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/pathSerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/pathSerializer.gen.ts new file mode 100644 index 0000000000..994b2848c6 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/pathSerializer.gen.ts @@ -0,0 +1,171 @@ +// This file is auto-generated by @hey-api/openapi-ts + +interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} + +interface SerializePrimitiveOptions { + allowReserved?: boolean; + name: string; +} + +export interface SerializerOptions { + /** + * @default true + */ + explode: boolean; + style: T; +} + +export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; +export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; +type MatrixStyle = 'label' | 'matrix' | 'simple'; +export type ObjectStyle = 'form' | 'deepObject'; +type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; + +interface SerializePrimitiveParam extends SerializePrimitiveOptions { + value: string; +} + +export const separatorArrayExplode = (style: ArraySeparatorStyle) => { + switch (style) { + case 'label': + return '.'; + case 'matrix': + return ';'; + case 'simple': + return ','; + default: + return '&'; + } +}; + +export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { + switch (style) { + case 'form': + return ','; + case 'pipeDelimited': + return '|'; + case 'spaceDelimited': + return '%20'; + default: + return ','; + } +}; + +export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { + switch (style) { + case 'label': + return '.'; + case 'matrix': + return ';'; + case 'simple': + return ','; + default: + return '&'; + } +}; + +export const serializeArrayParam = ({ + allowReserved, + explode, + name, + style, + value, +}: SerializeOptions & { + value: unknown[]; +}) => { + if (!explode) { + const joinedValues = ( + allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) + ).join(separatorArrayNoExplode(style)); + switch (style) { + case 'label': + return `.${joinedValues}`; + case 'matrix': + return `;${name}=${joinedValues}`; + case 'simple': + return joinedValues; + default: + return `${name}=${joinedValues}`; + } + } + + const separator = separatorArrayExplode(style); + const joinedValues = value + .map((v) => { + if (style === 'label' || style === 'simple') { + return allowReserved ? v : encodeURIComponent(v as string); + } + + return serializePrimitiveParam({ + allowReserved, + name, + value: v as string, + }); + }) + .join(separator); + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; +}; + +export const serializePrimitiveParam = ({ + allowReserved, + name, + value, +}: SerializePrimitiveParam) => { + if (value === undefined || value === null) { + return ''; + } + + if (typeof value === 'object') { + throw new Error( + 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', + ); + } + + return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; +}; + +export const serializeObjectParam = ({ + allowReserved, + explode, + name, + style, + value, + valueOnly, +}: SerializeOptions & { + value: Record | Date; + valueOnly?: boolean; +}) => { + if (value instanceof Date) { + return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; + } + + if (style !== 'deepObject' && !explode) { + let values: string[] = []; + Object.entries(value).forEach(([key, v]) => { + values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; + }); + const joinedValues = values.join(','); + switch (style) { + case 'form': + return `${name}=${joinedValues}`; + case 'label': + return `.${joinedValues}`; + case 'matrix': + return `;${name}=${joinedValues}`; + default: + return joinedValues; + } + } + + const separator = separatorObjectExplode(style); + const joinedValues = Object.entries(value) + .map(([key, v]) => + serializePrimitiveParam({ + allowReserved, + name: style === 'deepObject' ? `${name}[${key}]` : key, + value: v as string, + }), + ) + .join(separator); + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/queryKeySerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/queryKeySerializer.gen.ts new file mode 100644 index 0000000000..5000df606f --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/queryKeySerializer.gen.ts @@ -0,0 +1,117 @@ +// This file is auto-generated by @hey-api/openapi-ts + +/** + * JSON-friendly union that mirrors what Pinia Colada can hash. + */ +export type JsonValue = + | null + | string + | number + | boolean + | JsonValue[] + | { [key: string]: JsonValue }; + +/** + * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. + */ +export const queryKeyJsonReplacer = (_key: string, value: unknown) => { + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { + return undefined; + } + if (typeof value === 'bigint') { + return value.toString(); + } + if (value instanceof Date) { + return value.toISOString(); + } + return value; +}; + +/** + * Safely stringifies a value and parses it back into a JsonValue. + */ +export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { + try { + const json = JSON.stringify(input, queryKeyJsonReplacer); + if (json === undefined) { + return undefined; + } + return JSON.parse(json) as JsonValue; + } catch { + return undefined; + } +}; + +/** + * Detects plain objects (including objects with a null prototype). + */ +const isPlainObject = (value: unknown): value is Record => { + if (value === null || typeof value !== 'object') { + return false; + } + const prototype = Object.getPrototypeOf(value as object); + return prototype === Object.prototype || prototype === null; +}; + +/** + * Turns URLSearchParams into a sorted JSON object for deterministic keys. + */ +const serializeSearchParams = (params: URLSearchParams): JsonValue => { + const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); + const result: Record = {}; + + for (const [key, value] of entries) { + const existing = result[key]; + if (existing === undefined) { + result[key] = value; + continue; + } + + if (Array.isArray(existing)) { + (existing as string[]).push(value); + } else { + result[key] = [existing, value]; + } + } + + return result; +}; + +/** + * Normalizes any accepted value into a JSON-friendly shape for query keys. + */ +export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { + if (value === null) { + return null; + } + + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return value; + } + + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { + return undefined; + } + + if (typeof value === 'bigint') { + return value.toString(); + } + + if (value instanceof Date) { + return value.toISOString(); + } + + if (Array.isArray(value)) { + return stringifyToJsonValue(value); + } + + if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { + return serializeSearchParams(value); + } + + if (isPlainObject(value)) { + return stringifyToJsonValue(value); + } + + return undefined; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/serverSentEvents.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/serverSentEvents.gen.ts new file mode 100644 index 0000000000..6aa6cf02a4 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/serverSentEvents.gen.ts @@ -0,0 +1,243 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Config } from './types.gen'; + +export type ServerSentEventsOptions = Omit & + Pick & { + /** + * Fetch API implementation. You can use this option to provide a custom + * fetch instance. + * + * @default globalThis.fetch + */ + fetch?: typeof fetch; + /** + * Implementing clients can call request interceptors inside this hook. + */ + onRequest?: (url: string, init: RequestInit) => Promise; + /** + * Callback invoked when a network or parsing error occurs during streaming. + * + * This option applies only if the endpoint returns a stream of events. + * + * @param error The error that occurred. + */ + onSseError?: (error: unknown) => void; + /** + * Callback invoked when an event is streamed from the server. + * + * This option applies only if the endpoint returns a stream of events. + * + * @param event Event streamed from the server. + * @returns Nothing (void). + */ + onSseEvent?: (event: StreamEvent) => void; + serializedBody?: RequestInit['body']; + /** + * Default retry delay in milliseconds. + * + * This option applies only if the endpoint returns a stream of events. + * + * @default 3000 + */ + sseDefaultRetryDelay?: number; + /** + * Maximum number of retry attempts before giving up. + */ + sseMaxRetryAttempts?: number; + /** + * Maximum retry delay in milliseconds. + * + * Applies only when exponential backoff is used. + * + * This option applies only if the endpoint returns a stream of events. + * + * @default 30000 + */ + sseMaxRetryDelay?: number; + /** + * Optional sleep function for retry backoff. + * + * Defaults to using `setTimeout`. + */ + sseSleepFn?: (ms: number) => Promise; + url: string; + }; + +export interface StreamEvent { + data: TData; + event?: string; + id?: string; + retry?: number; +} + +export type ServerSentEventsResult = { + stream: AsyncGenerator< + TData extends Record ? TData[keyof TData] : TData, + TReturn, + TNext + >; +}; + +export const createSseClient = ({ + onRequest, + onSseError, + onSseEvent, + responseTransformer, + responseValidator, + sseDefaultRetryDelay, + sseMaxRetryAttempts, + sseMaxRetryDelay, + sseSleepFn, + url, + ...options +}: ServerSentEventsOptions): ServerSentEventsResult => { + let lastEventId: string | undefined; + + const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + + const createStream = async function* () { + let retryDelay: number = sseDefaultRetryDelay ?? 3000; + let attempt = 0; + const signal = options.signal ?? new AbortController().signal; + + while (true) { + if (signal.aborted) break; + + attempt++; + + const headers = + options.headers instanceof Headers + ? options.headers + : new Headers(options.headers as Record | undefined); + + if (lastEventId !== undefined) { + headers.set('Last-Event-ID', lastEventId); + } + + try { + const requestInit: RequestInit = { + redirect: 'follow', + ...options, + body: options.serializedBody, + headers, + signal, + }; + let request = new Request(url, requestInit); + if (onRequest) { + request = await onRequest(url, requestInit); + } + // fetch must be assigned here, otherwise it would throw the error: + // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation + const _fetch = options.fetch ?? globalThis.fetch; + const response = await _fetch(request); + + if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); + + if (!response.body) throw new Error('No body in SSE response'); + + const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); + + let buffer = ''; + + const abortHandler = () => { + try { + reader.cancel(); + } catch { + // noop + } + }; + + signal.addEventListener('abort', abortHandler); + + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + buffer += value; + // Normalize line endings: CRLF -> LF, then CR -> LF + buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); + + const chunks = buffer.split('\n\n'); + buffer = chunks.pop() ?? ''; + + for (const chunk of chunks) { + const lines = chunk.split('\n'); + const dataLines: Array = []; + let eventName: string | undefined; + + for (const line of lines) { + if (line.startsWith('data:')) { + dataLines.push(line.replace(/^data:\s*/, '')); + } else if (line.startsWith('event:')) { + eventName = line.replace(/^event:\s*/, ''); + } else if (line.startsWith('id:')) { + lastEventId = line.replace(/^id:\s*/, ''); + } else if (line.startsWith('retry:')) { + const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); + if (!Number.isNaN(parsed)) { + retryDelay = parsed; + } + } + } + + let data: unknown; + let parsedJson = false; + + if (dataLines.length) { + const rawData = dataLines.join('\n'); + try { + data = JSON.parse(rawData); + parsedJson = true; + } catch { + data = rawData; + } + } + + if (parsedJson) { + if (responseValidator) { + await responseValidator(data); + } + + if (responseTransformer) { + data = await responseTransformer(data); + } + } + + onSseEvent?.({ + data, + event: eventName, + id: lastEventId, + retry: retryDelay, + }); + + if (dataLines.length) { + yield data as any; + } + } + } + } finally { + signal.removeEventListener('abort', abortHandler); + reader.releaseLock(); + } + + break; // exit loop on normal completion + } catch (error) { + // connection failed or aborted; retry after delay + onSseError?.(error); + + if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { + break; // stop after firing error + } + + // exponential backoff: double retry each attempt, cap at 30s + const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); + await sleep(backoff); + } + } + }; + + const stream = createStream(); + + return { stream }; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/types.gen.ts new file mode 100644 index 0000000000..97463257e4 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/types.gen.ts @@ -0,0 +1,104 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Auth, AuthToken } from './auth.gen'; +import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; + +export type HttpMethod = + | 'connect' + | 'delete' + | 'get' + | 'head' + | 'options' + | 'patch' + | 'post' + | 'put' + | 'trace'; + +export type Client< + RequestFn = never, + Config = unknown, + MethodFn = never, + BuildUrlFn = never, + SseFn = never, +> = { + /** + * Returns the final request URL. + */ + buildUrl: BuildUrlFn; + getConfig: () => Config; + request: RequestFn; + setConfig: (config: Config) => Config; +} & { + [K in HttpMethod]: MethodFn; +} & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); + +export interface Config { + /** + * Auth token or a function returning auth token. The resolved value will be + * added to the request payload as defined by its `security` array. + */ + auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; + /** + * A function for serializing request body parameter. By default, + * {@link JSON.stringify()} will be used. + */ + bodySerializer?: BodySerializer | null; + /** + * An object containing any HTTP headers that you want to pre-populate your + * `Headers` object with. + * + * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} + */ + headers?: + | RequestInit['headers'] + | Record< + string, + string | number | boolean | (string | number | boolean)[] | null | undefined | unknown + >; + /** + * The request method. + * + * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} + */ + method?: Uppercase; + /** + * A function for serializing request query parameters. By default, arrays + * will be exploded in form style, objects will be exploded in deepObject + * style, and reserved characters are percent-encoded. + * + * This method will have no effect if the native `paramsSerializer()` Axios + * API function is used. + * + * {@link https://swagger.io/docs/specification/serialization/#query View examples} + */ + querySerializer?: QuerySerializer | QuerySerializerOptions; + /** + * A function validating request data. This is useful if you want to ensure + * the request conforms to the desired shape, so it can be safely sent to + * the server. + */ + requestValidator?: (data: unknown) => Promise; + /** + * A function transforming response data before it's returned. This is useful + * for post-processing data, e.g. converting ISO strings into Date objects. + */ + responseTransformer?: (data: unknown) => Promise; + /** + * A function validating response data. This is useful if you want to ensure + * the response conforms to the desired shape, so it can be safely passed to + * the transformers and returned to the user. + */ + responseValidator?: (data: unknown) => Promise; +} + +type IsExactlyNeverOrNeverUndefined = [T] extends [never] + ? true + : [T] extends [never | undefined] + ? [undefined] extends [T] + ? false + : true + : false; + +export type OmitNever> = { + [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/utils.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/utils.gen.ts new file mode 100644 index 0000000000..e7ddbe3541 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/core/utils.gen.ts @@ -0,0 +1,140 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; +import { + type ArraySeparatorStyle, + serializeArrayParam, + serializeObjectParam, + serializePrimitiveParam, +} from './pathSerializer.gen'; + +export interface PathSerializer { + path: Record; + url: string; +} + +export const PATH_PARAM_RE = /\{[^{}]+\}/g; + +export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { + let url = _url; + const matches = _url.match(PATH_PARAM_RE); + if (matches) { + for (const match of matches) { + let explode = false; + let name = match.substring(1, match.length - 1); + let style: ArraySeparatorStyle = 'simple'; + + if (name.endsWith('*')) { + explode = true; + name = name.substring(0, name.length - 1); + } + + if (name.startsWith('.')) { + name = name.substring(1); + style = 'label'; + } else if (name.startsWith(';')) { + name = name.substring(1); + style = 'matrix'; + } + + const value = path[name]; + + if (value === undefined || value === null) { + continue; + } + + if (Array.isArray(value)) { + url = url.replace(match, serializeArrayParam({ explode, name, style, value })); + continue; + } + + if (typeof value === 'object') { + url = url.replace( + match, + serializeObjectParam({ + explode, + name, + style, + value: value as Record, + valueOnly: true, + }), + ); + continue; + } + + if (style === 'matrix') { + url = url.replace( + match, + `;${serializePrimitiveParam({ + name, + value: value as string, + })}`, + ); + continue; + } + + const replaceValue = encodeURIComponent( + style === 'label' ? `.${value as string}` : (value as string), + ); + url = url.replace(match, replaceValue); + } + } + return url; +}; + +export const getUrl = ({ + baseUrl, + path, + query, + querySerializer, + url: _url, +}: { + baseUrl?: string; + path?: Record; + query?: Record; + querySerializer: QuerySerializer; + url: string; +}) => { + const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; + let url = (baseUrl ?? '') + pathUrl; + if (path) { + url = defaultPathSerializer({ path, url }); + } + let search = query ? querySerializer(query) : ''; + if (search.startsWith('?')) { + search = search.substring(1); + } + if (search) { + url += `?${search}`; + } + return url; +}; + +export function getValidRequestBody(options: { + body?: unknown; + bodySerializer?: BodySerializer | null; + serializedBody?: unknown; +}) { + const hasBody = options.body !== undefined; + const isSerializedBody = hasBody && options.bodySerializer; + + if (isSerializedBody) { + if ('serializedBody' in options) { + const hasSerializedBody = + options.serializedBody !== undefined && options.serializedBody !== ''; + + return hasSerializedBody ? options.serializedBody : null; + } + + // not all clients implement a serializedBody property (i.e. client-axios) + return options.body !== '' ? options.body : null; + } + + // plain/text body + if (hasBody) { + return options.body; + } + + // no body was provided + return undefined; +} diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/index.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/index.ts new file mode 100644 index 0000000000..ee6d0288c0 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/index.ts @@ -0,0 +1,4 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from './sdk.gen'; +export type { ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, Date, Default, DeleteCallWithoutParametersAndResponseData, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithStrings, ExternalRefA, ExternalRefB, ExternalSharedModel, FailureFailure, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ModelThatExtends, ModelThatExtendsExtends, ModelWithArray, ModelWithBoolean, ModelWithCircularReference, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithInteger, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableString, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, OptionsCallWithoutParametersAndResponseData, ParameterActivityParams, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyError, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponse, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ResponsePostActivityResponse, ServiceWithEmptyTagData, SimpleBoolean, SimpleFile, SimpleInteger, SimpleReference, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses } from './types.gen'; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/sdk.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/sdk.gen.ts new file mode 100644 index 0000000000..6776488ce6 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/sdk.gen.ts @@ -0,0 +1,127 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Client, Options as Options2, TDataShape } from './client'; +import { client } from './client.gen'; +import type { CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, FooWowData, FooWowResponses, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionBodyData, PostApiVbyApiVersionBodyErrors, PostApiVbyApiVersionBodyResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, ServiceWithEmptyTagData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses } from './types.gen'; + +export type Options = Options2 & { + /** + * You can provide a client instance returned by `createClient()` instead of + * individual options. This might be also useful if you want to implement a + * custom client. + */ + client?: Client; + /** + * You can pass arbitrary values through the `meta` object. This can be + * used to access values that aren't defined as part of the SDK function. + */ + meta?: Record; +}; + +export const serviceWithEmptyTag = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); + +export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); + +export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); + +export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); + +export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); + +export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); + +export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); + +export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); + +export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); + +export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); + +export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions/', ...options }); + +export const callWithParameters = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/{parameterPath}', ...options }); + +export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const callWithDefaultParameters = (options: Options) => (options.client ?? client).get({ + querySerializer: { parameters: { parameterModel: { object: { explode: false, style: 'form' } } } }, + url: '/api/v{api-version}/defaults', + ...options +}); + +export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); + +export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); + +export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); + +export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); + +export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); + +export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); + +export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); + +export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); + +export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); + +export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); + +export const collectionFormat = (options: Options) => (options.client ?? client).get({ + querySerializer: { parameters: { + parameterArrayCSV: { array: { explode: false } }, + parameterArraySSV: { array: { explode: false } }, + parameterArrayTSV: { array: { explode: false } }, + parameterArrayPipes: { array: { explode: false } } + } }, + url: '/api/v{api-version}/collectionFormat', + ...options +}); + +export const types = (options: Options) => (options.client ?? client).get({ + querySerializer: { parameters: { parameterArray: { array: { explode: false } }, parameterDictionary: { object: { explode: false, style: 'form' } } } }, + url: '/api/v{api-version}/types', + ...options +}); + +export const complexTypes = (options: Options) => (options.client ?? client).get({ + querySerializer: { parameters: { parameterObject: { object: { explode: false, style: 'form' } }, parameterReference: { object: { explode: false, style: 'form' } } } }, + url: '/api/v{api-version}/complex', + ...options +}); + +export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); + +export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); + +export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); + +/** + * Body should not be unknown + * + * Body should not be unknown + */ +export const postApiVbyApiVersionBody = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/body', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/types.gen.ts new file mode 100644 index 0000000000..d69b074040 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/react-query/useQuery/types.gen.ts @@ -0,0 +1,1190 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type ClientOptions = { + baseUrl: 'http://localhost:3000/base' | (string & {}); +}; + +export type ExternalRefA = ExternalSharedModel; + +export type ExternalRefB = ExternalSharedModel; + +/** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ +export type CommentWithBreaks = number; + +/** + * Testing backticks in string: `backticks` and ```multiple backticks``` should work + */ +export type CommentWithBackticks = number; + +/** + * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work + */ +export type CommentWithBackticksAndQuotes = number; + +/** + * Testing slashes in string: \backwards\\\ and /forwards/// should work + */ +export type CommentWithSlashes = number; + +/** + * Testing expression placeholders in string: ${expression} should work + */ +export type CommentWithExpressionPlaceholders = number; + +/** + * Testing quotes in string: 'single quote''' and "double quotes""" should work + */ +export type CommentWithQuotes = number; + +/** + * Testing reserved characters in string: * inline * and ** inline ** should work + */ +export type CommentWithReservedCharacters = number; + +/** + * This is a simple number + */ +export type SimpleInteger = number; + +/** + * This is a simple boolean + */ +export type SimpleBoolean = boolean; + +/** + * This is a simple string + */ +export type SimpleString = string; + +/** + * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) + */ +export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; + +/** + * This is a simple file + */ +export type SimpleFile = Blob | File; + +export type SimpleReference = ModelWithString; + +/** + * This is a simple string + */ +export type SimpleStringWithPattern = string; + +/** + * This is a simple enum with strings + */ +export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; + +/** + * This is a simple enum with numbers + */ +export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; + +/** + * Success=1,Warning=2,Error=3 + */ +export type EnumFromDescription = number; + +/** + * This is a simple enum with numbers + */ +export type EnumWithExtensions = 200 | 400 | 500; + +/** + * This is a simple array with numbers + */ +export type ArrayWithNumbers = Array; + +/** + * This is a simple array with booleans + */ +export type ArrayWithBooleans = Array; + +/** + * This is a simple array with strings + */ +export type ArrayWithStrings = Array; + +/** + * This is a simple array with references + */ +export type ArrayWithReferences = Array; + +/** + * This is a simple array containing an array + */ +export type ArrayWithArray = Array>; + +/** + * This is a simple array with properties + */ +export type ArrayWithProperties = Array<{ + foo?: string; + bar?: string; +}>; + +/** + * This is a string dictionary + */ +export type DictionaryWithString = { + [key: string]: string; +}; + +/** + * This is a string reference + */ +export type DictionaryWithReference = { + [key: string]: ModelWithString; +}; + +/** + * This is a complex dictionary + */ +export type DictionaryWithArray = { + [key: string]: Array; +}; + +/** + * This is a string dictionary + */ +export type DictionaryWithDictionary = { + [key: string]: { + [key: string]: string; + }; +}; + +/** + * This is a complex dictionary + */ +export type DictionaryWithProperties = { + [key: string]: { + foo?: string; + bar?: string; + }; +}; + +/** + * This is a type-only model that defines Date as a string + */ +export type Date = string; + +/** + * This is a model with one number property + */ +export type ModelWithInteger = { + /** + * This is a simple number property + */ + prop?: number; +}; + +/** + * This is a model with one boolean property + */ +export type ModelWithBoolean = { + /** + * This is a simple boolean property + */ + prop?: boolean; +}; + +/** + * This is a model with one string property + */ +export type ModelWithString = { + /** + * This is a simple string property + */ + prop?: string; +}; + +/** + * This is a model with one string property + */ +export type ModelWithStringError = { + /** + * This is a simple string property + */ + prop?: string; +}; + +/** + * This is a model with one string property + */ +export type ModelWithNullableString = { + /** + * This is a simple string property + */ + nullableProp?: string | null; + /** + * This is a simple string property + */ + nullableRequiredProp: string | null; +}; + +/** + * This is a model with one enum + */ +export type ModelWithEnum = { + /** + * This is a simple enum with strings + */ + test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; + /** + * These are the HTTP error code enums + */ + statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; + /** + * Simple boolean enum + */ + bool?: true; +}; + +/** + * This is a model with one enum + */ +export type ModelWithEnumFromDescription = { + /** + * Success=1,Warning=2,Error=3 + */ + test?: number; +}; + +/** + * This is a model with nested enums + */ +export type ModelWithNestedEnums = { + dictionaryWithEnum?: { + [key: string]: 'Success' | 'Warning' | 'Error'; + }; + dictionaryWithEnumFromDescription?: { + [key: string]: number; + }; + arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; + arrayWithDescription?: Array; +}; + +/** + * This is a model with one property containing a reference + */ +export type ModelWithReference = { + prop?: ModelWithProperties; +}; + +/** + * This is a model with one property containing an array + */ +export type ModelWithArray = { + prop?: Array; + propWithFile?: Array; + propWithNumber?: Array; +}; + +/** + * This is a model with one property containing a dictionary + */ +export type ModelWithDictionary = { + prop?: { + [key: string]: string; + }; +}; + +/** + * This is a model with one property containing a circular reference + */ +export type ModelWithCircularReference = { + prop?: ModelWithCircularReference; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithProperties = { + required: string; + readonly requiredAndReadOnly: string; + string?: string; + number?: number; + boolean?: boolean; + reference?: ModelWithString; + 'property with space'?: string; + default?: string; + try?: string; + readonly '@namespace.string'?: string; + readonly '@namespace.integer'?: number; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithNestedProperties = { + readonly first: { + readonly second: { + readonly third: string; + }; + }; +}; + +/** + * This is a model with duplicated properties + */ +export type ModelWithDuplicateProperties = { + prop?: ModelWithString; +}; + +/** + * This is a model with ordered properties + */ +export type ModelWithOrderedProperties = { + zebra?: string; + apple?: string; + hawaii?: string; +}; + +/** + * This is a model with duplicated imports + */ +export type ModelWithDuplicateImports = { + propA?: ModelWithString; + propB?: ModelWithString; + propC?: ModelWithString; +}; + +/** + * This is a model that extends another model + */ +export type ModelThatExtends = ModelWithString & { + propExtendsA?: string; + propExtendsB?: ModelWithString; +}; + +/** + * This is a model that extends another model + */ +export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { + propExtendsC?: string; + propExtendsD?: ModelWithString; +}; + +export type Default = { + name?: string; +}; + +/** + * This is a model that contains a some patterns + */ +export type ModelWithPattern = { + key: string; + name: string; + readonly enabled?: boolean; + readonly modified?: string; + id?: string; + text?: string; + patternWithSingleQuotes?: string; + patternWithNewline?: string; + patternWithBacktick?: string; + patternWithUnicode?: string; +}; + +export type ParameterActivityParams = { + description?: string; + graduate_id?: number; + organization_id?: number; + parent_activity?: number; + post_id?: number; +}; + +export type ResponsePostActivityResponse = { + description?: string; + graduate_id?: number; + organization_id?: number; + parent_activity_id?: number; + post_id?: number; +}; + +export type FailureFailure = { + error?: string; + message?: string; + reference_code?: string; +}; + +export type ExternalSharedModel = { + id: string; + name?: string; +}; + +/** + * This is a model with one property containing a reference + */ +export type ModelWithReferenceWritable = { + prop?: ModelWithPropertiesWritable; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithPropertiesWritable = { + required: string; + string?: string; + number?: number; + boolean?: boolean; + reference?: ModelWithString; + 'property with space'?: string; + default?: string; + try?: string; +}; + +/** + * This is a model that contains a some patterns + */ +export type ModelWithPatternWritable = { + key: string; + name: string; + id?: string; + text?: string; + patternWithSingleQuotes?: string; + patternWithNewline?: string; + patternWithBacktick?: string; + patternWithUnicode?: string; +}; + +export type ServiceWithEmptyTagData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type PatchApiVbyApiVersionNoTagData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type PatchApiVbyApiVersionNoTagResponses = { + /** + * OK + */ + default: unknown; +}; + +export type FooWowData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type FooWowResponses = { + /** + * OK + */ + default: unknown; +}; + +export type DeleteCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type GetCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type HeadCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type OptionsCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PatchCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PostCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PutCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type CallWithDescriptionsData = { + body?: never; + path?: never; + query?: { + /** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ + parameterWithBreaks?: string; + /** + * Testing backticks in string: `backticks` and ```multiple backticks``` should work + */ + parameterWithBackticks?: string; + /** + * Testing slashes in string: \backwards\\\ and /forwards/// should work + */ + parameterWithSlashes?: string; + /** + * Testing expression placeholders in string: ${expression} should work + */ + parameterWithExpressionPlaceholders?: string; + /** + * Testing quotes in string: 'single quote''' and "double quotes""" should work + */ + parameterWithQuotes?: string; + /** + * Testing reserved characters in string: * inline * and ** inline ** should work + */ + parameterWithReservedCharacters?: string; + }; + url: '/api/v{api-version}/descriptions/'; +}; + +export type CallWithParametersData = { + body?: never; + headers: { + /** + * This is the parameter that goes into the header + */ + parameterHeader: string; + }; + path: { + /** + * This is the parameter that goes into the path + */ + parameterPath: string; + /** + * api-version should be required in standalone clients + */ + 'api-version': string; + }; + query: { + /** + * This is the parameter that goes into the query params + */ + parameterQuery: string; + }; + url: '/api/v{api-version}/parameters/{parameterPath}'; +}; + +export type CallWithWeirdParameterNamesData = { + /** + * This is the parameter that is sent as request body + */ + body: string; + headers: { + /** + * This is the parameter that goes into the request header + */ + 'parameter.header': string; + }; + path: { + /** + * This is the parameter that goes into the path + */ + 'parameter.path.1'?: string; + /** + * This is the parameter that goes into the path + */ + 'parameter-path-2'?: string; + /** + * This is the parameter that goes into the path + */ + 'PARAMETER-PATH-3'?: string; + /** + * api-version should be required in standalone clients + */ + 'api-version': string; + }; + query: { + /** + * This is the parameter with a reserved keyword + */ + default?: string; + /** + * This is the parameter that goes into the request query params + */ + 'parameter-query': string; + }; + url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; +}; + +export type CallWithDefaultParametersData = { + body?: never; + path?: never; + query: { + /** + * This is a simple string with default value + */ + parameterString: string; + /** + * This is a simple number with default value + */ + parameterNumber: number; + /** + * This is a simple boolean with default value + */ + parameterBoolean: boolean; + /** + * This is a simple enum with default value + */ + parameterEnum: 'Success' | 'Warning' | 'Error'; + /** + * This is a model with one string property + */ + parameterModel: { + /** + * This is a simple string property + */ + prop?: string; + }; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type CallWithDefaultOptionalParametersData = { + body?: never; + path?: never; + query?: { + /** + * This is a simple string that is optional with default value + */ + parameterString?: string; + /** + * This is a simple number that is optional with default value + */ + parameterNumber?: number; + /** + * This is a simple boolean that is optional with default value + */ + parameterBoolean?: boolean; + /** + * This is a simple enum that is optional with default value + */ + parameterEnum?: 'Success' | 'Warning' | 'Error'; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type CallToTestOrderOfParamsData = { + body?: never; + path?: never; + query: { + /** + * This is a optional string with default + */ + parameterOptionalStringWithDefault?: string; + /** + * This is a optional string with empty default + */ + parameterOptionalStringWithEmptyDefault?: string; + /** + * This is a optional string with no default + */ + parameterOptionalStringWithNoDefault?: string; + /** + * This is a string with default + */ + parameterStringWithDefault: string; + /** + * This is a string with empty default + */ + parameterStringWithEmptyDefault: string; + /** + * This is a string with no default + */ + parameterStringWithNoDefault: string; + /** + * This is a string that can be null with no default + */ + parameterStringNullableWithNoDefault?: string | null; + /** + * This is a string that can be null with default + */ + parameterStringNullableWithDefault?: string | null; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type DuplicateNameData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName2Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName3Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName4Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type CallWithNoContentResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no-content'; +}; + +export type CallWithNoContentResponseResponses = { + /** + * Success + */ + 204: unknown; +}; + +export type CallWithResponseAndNoContentResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/response-and-no-content'; +}; + +export type CallWithResponseAndNoContentResponseResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Success + */ + 204: unknown; +}; + +export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; + +export type DummyAData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/a'; +}; + +export type DummyAResponses = { + /** + * Success + */ + 204: unknown; +}; + +export type DummyBData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/b'; +}; + +export type DummyBResponses = { + /** + * Success + */ + 204: unknown; +}; + +export type CallWithResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithResponseResponses = { + /** + * Message for default response + */ + default: ModelWithString; +}; + +export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; + +export type CallWithDuplicateResponsesData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithDuplicateResponsesErrors = { + /** + * Message for 500 error + */ + 500: ModelWithStringError; + /** + * Message for 501 error + */ + 501: ModelWithStringError; + /** + * Message for 502 error + */ + 502: ModelWithStringError; + /** + * Message for default response + */ + default: ModelWithString; +}; + +export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; + +export type CallWithDuplicateResponsesResponses = { + /** + * Message for 201 response + */ + 201: ModelWithString; + /** + * Message for 202 response + */ + 202: ModelWithString; +}; + +export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; + +export type CallWithResponsesData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithResponsesErrors = { + /** + * Message for 500 error + */ + 500: ModelWithStringError; + /** + * Message for 501 error + */ + 501: ModelWithStringError; + /** + * Message for 502 error + */ + 502: ModelWithStringError; + /** + * Message for default response + */ + default: ModelWithString; +}; + +export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; + +export type CallWithResponsesResponses = { + /** + * Message for 200 response + */ + 200: { + readonly '@namespace.string'?: string; + readonly '@namespace.integer'?: number; + readonly value?: Array; + }; + /** + * Message for 201 response + */ + 201: ModelThatExtends; + /** + * Message for 202 response + */ + 202: ModelThatExtendsExtends; +}; + +export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; + +export type CollectionFormatData = { + body?: never; + path?: never; + query: { + /** + * This is an array parameter that is sent as csv format (comma-separated values) + */ + parameterArrayCSV: Array; + /** + * This is an array parameter that is sent as ssv format (space-separated values) + */ + parameterArraySSV: Array; + /** + * This is an array parameter that is sent as tsv format (tab-separated values) + */ + parameterArrayTSV: Array; + /** + * This is an array parameter that is sent as pipes format (pipe-separated values) + */ + parameterArrayPipes: Array; + /** + * This is an array parameter that is sent as multi format (multiple parameter instances) + */ + parameterArrayMulti: Array; + }; + url: '/api/v{api-version}/collectionFormat'; +}; + +export type TypesData = { + body?: never; + path?: { + /** + * This is a number parameter + */ + id?: number; + }; + query: { + /** + * This is a number parameter + */ + parameterNumber: number; + /** + * This is a string parameter + */ + parameterString: string; + /** + * This is a boolean parameter + */ + parameterBoolean: boolean; + /** + * This is an array parameter + */ + parameterArray: Array; + /** + * This is a dictionary parameter + */ + parameterDictionary: { + [key: string]: unknown; + }; + /** + * This is an enum parameter + */ + parameterEnum: 'Success' | 'Warning' | 'Error'; + }; + url: '/api/v{api-version}/types'; +}; + +export type TypesResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Response is a simple string + */ + 201: string; + /** + * Response is a simple boolean + */ + 202: boolean; + /** + * Response is a simple object + */ + 203: { + [key: string]: unknown; + }; +}; + +export type TypesResponse = TypesResponses[keyof TypesResponses]; + +export type ComplexTypesData = { + body?: never; + path?: never; + query: { + /** + * Parameter containing object + */ + parameterObject: { + first?: { + second?: { + third?: string; + }; + }; + }; + /** + * This is a model with one string property + */ + parameterReference: { + /** + * This is a simple string property + */ + prop?: string; + }; + }; + url: '/api/v{api-version}/complex'; +}; + +export type ComplexTypesErrors = { + /** + * 400 server error + */ + 400: unknown; + /** + * 500 server error + */ + 500: unknown; +}; + +export type ComplexTypesResponses = { + /** + * Successful response + */ + 200: Array; +}; + +export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; + +export type CallWithResultFromHeaderData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/header'; +}; + +export type CallWithResultFromHeaderErrors = { + /** + * 400 server error + */ + 400: unknown; + /** + * 500 server error + */ + 500: unknown; +}; + +export type CallWithResultFromHeaderResponses = { + /** + * Successful response + */ + 200: unknown; +}; + +export type TestErrorCodeData = { + body?: never; + path?: never; + query: { + /** + * Status code to return + */ + status: string; + }; + url: '/api/v{api-version}/error'; +}; + +export type TestErrorCodeErrors = { + /** + * Custom message: Internal Server Error + */ + 500: unknown; + /** + * Custom message: Not Implemented + */ + 501: unknown; + /** + * Custom message: Bad Gateway + */ + 502: unknown; + /** + * Custom message: Service Unavailable + */ + 503: unknown; +}; + +export type TestErrorCodeResponses = { + /** + * Custom message: Successful response + */ + 200: unknown; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Data = { + body?: never; + path?: never; + query: { + /** + * Dummy input param + */ + nonAsciiParamæøåÆØÅöôêÊ: number; + }; + url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { + /** + * Successful response + */ + 200: NonAsciiStringæøåÆøÅöôêÊ字符串; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; + +export type PostApiVbyApiVersionBodyData = { + /** + * Body should not be unknown + */ + body: ParameterActivityParams; + path?: never; + query?: never; + url: '/api/v{api-version}/body'; +}; + +export type PostApiVbyApiVersionBodyErrors = { + /** + * Bad Request + */ + 400: FailureFailure; + /** + * Internal Server Error + */ + 500: FailureFailure; +}; + +export type PostApiVbyApiVersionBodyError = PostApiVbyApiVersionBodyErrors[keyof PostApiVbyApiVersionBodyErrors]; + +export type PostApiVbyApiVersionBodyResponses = { + /** + * OK + */ + 200: ResponsePostActivityResponse; +}; + +export type PostApiVbyApiVersionBodyResponse = PostApiVbyApiVersionBodyResponses[keyof PostApiVbyApiVersionBodyResponses]; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/asClass/@tanstack/solid-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/asClass/@tanstack/solid-query.gen.ts index d5594064cc..4c3bc16520 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/asClass/@tanstack/solid-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/asClass/@tanstack/solid-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/solid-query'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/solid-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooOptions = (options?: Options) => queryOptions>): MutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutMutation = (options?: Partial>): Mutation export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarOptions = (options?: Options) => queryOptio throwOnError: true }); return data; - }, - queryKey: getFooBarQueryKey(options) + }), + queryKey: getFooBarQueryKey(resolveOptions(options)) }); export const fooBarPostMutation = (options?: Partial>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/axios/@tanstack/solid-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/axios/@tanstack/solid-query.gen.ts index 7a51e436a3..717a737ff5 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/axios/@tanstack/solid-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/axios/@tanstack/solid-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/solid-query'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/solid-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; @@ -40,10 +40,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); -export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const serviceWithEmptyTagOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], @@ -51,8 +55,8 @@ export const serviceWithEmptyTagOptions = (options?: Options>): MutationOptions, Options> => { @@ -99,8 +103,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -108,8 +112,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): MutationOptions, Options> => { @@ -198,8 +202,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -207,8 +211,8 @@ export const callWithDefaultParametersOptions = (options: Options>): MutationOptions, Options> => { @@ -255,8 +259,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -264,8 +268,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions, Options> => { @@ -298,8 +302,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -307,14 +311,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -322,14 +326,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -337,14 +341,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -352,14 +356,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -367,8 +371,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions, Options> => { @@ -401,8 +405,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -410,14 +414,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions, TypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -425,14 +429,14 @@ export const typesOptions = (options: Options) => queryOptions) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions, ComplexTypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -440,8 +444,8 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions, Options> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/fetch/@tanstack/solid-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/fetch/@tanstack/solid-query.gen.ts index c4092a30b9..a09ac7ee96 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/fetch/@tanstack/solid-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/fetch/@tanstack/solid-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/solid-query'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/solid-query'; import { client } from '../client.gen'; import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); -export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const serviceWithEmptyTagOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const serviceWithEmptyTagOptions = (options?: Options>): MutationOptions> => { @@ -98,8 +102,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -107,8 +111,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): MutationOptions> => { @@ -197,8 +201,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -206,8 +210,8 @@ export const callWithDefaultParametersOptions = (options: Options>): MutationOptions> => { @@ -254,8 +258,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -263,8 +267,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions> => { @@ -297,8 +301,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -306,14 +310,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -321,14 +325,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -336,14 +340,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -351,14 +355,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -366,8 +370,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions> => { @@ -400,8 +404,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -409,14 +413,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -424,14 +428,14 @@ export const typesOptions = (options: Options) => queryOptions) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -439,8 +443,8 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/name-builder/@tanstack/solid-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/name-builder/@tanstack/solid-query.gen.ts index ba1febdda4..c7ec98152f 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/name-builder/@tanstack/solid-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/solid-query/name-builder/@tanstack/solid-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/solid-query'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/solid-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooD = (options?: Options) => createQueryKey('getFoo', options); -export const getFooE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooE = (options?: Options) => queryOptions>): MutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutC = (options?: Partial>): MutationOptions export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarE = (options?: Options) => queryOptions>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/asClass/@tanstack/svelte-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/asClass/@tanstack/svelte-query.gen.ts index 3e29275971..af19b9b3eb 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/asClass/@tanstack/svelte-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/asClass/@tanstack/svelte-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/svelte-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooOptions = (options?: Options) => queryOptions>): MutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutMutation = (options?: Partial>): Mutation export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarOptions = (options?: Options) => queryOptio throwOnError: true }); return data; - }, - queryKey: getFooBarQueryKey(options) + }), + queryKey: getFooBarQueryKey(resolveOptions(options)) }); export const fooBarPostMutation = (options?: Partial>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/axios/@tanstack/svelte-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/axios/@tanstack/svelte-query.gen.ts index 8900d4a581..42e6c71673 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/axios/@tanstack/svelte-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/axios/@tanstack/svelte-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/svelte-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; @@ -40,10 +40,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); -export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const serviceWithEmptyTagOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], @@ -51,8 +55,8 @@ export const serviceWithEmptyTagOptions = (options?: Options>): MutationOptions, Options> => { @@ -99,8 +103,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -108,8 +112,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): MutationOptions, Options> => { @@ -198,8 +202,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -207,8 +211,8 @@ export const callWithDefaultParametersOptions = (options: Options>): MutationOptions, Options> => { @@ -255,8 +259,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -264,8 +268,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions, Options> => { @@ -298,8 +302,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -307,14 +311,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -322,14 +326,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -337,14 +341,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -352,14 +356,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -367,8 +371,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions, Options> => { @@ -401,8 +405,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -410,14 +414,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions, TypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -425,14 +429,14 @@ export const typesOptions = (options: Options) => queryOptions) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions, ComplexTypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -440,8 +444,8 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions, Options> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/fetch/@tanstack/svelte-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/fetch/@tanstack/svelte-query.gen.ts index e14c0d70c0..8acffb90d9 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/fetch/@tanstack/svelte-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/fetch/@tanstack/svelte-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/svelte-query'; import { client } from '../client.gen'; import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); -export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const serviceWithEmptyTagOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const serviceWithEmptyTagOptions = (options?: Options>): MutationOptions> => { @@ -98,8 +102,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -107,8 +111,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): MutationOptions> => { @@ -197,8 +201,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -206,8 +210,8 @@ export const callWithDefaultParametersOptions = (options: Options>): MutationOptions> => { @@ -254,8 +258,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -263,8 +267,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions> => { @@ -297,8 +301,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -306,14 +310,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -321,14 +325,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -336,14 +340,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -351,14 +355,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -366,8 +370,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions> => { @@ -400,8 +404,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -409,14 +413,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -424,14 +428,14 @@ export const typesOptions = (options: Options) => queryOptions) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -439,8 +443,8 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const callWithResultFromHeaderMutation = (options?: Partial>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/name-builder/@tanstack/svelte-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/name-builder/@tanstack/svelte-query.gen.ts index 6a831b5b3e..ad8c29d041 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/name-builder/@tanstack/svelte-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/svelte-query/name-builder/@tanstack/svelte-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/svelte-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooD = (options?: Options) => createQueryKey('getFoo', options); -export const getFooE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooE = (options?: Options) => queryOptions>): MutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutC = (options?: Partial>): MutationOptions export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarE = (options?: Options) => queryOptions>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/asClass/@tanstack/vue-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/asClass/@tanstack/vue-query.gen.ts index 2e82ca3558..317e2a873f 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/asClass/@tanstack/vue-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/asClass/@tanstack/vue-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions } from '@tanstack/vue-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooOptions = (options?: Options) => queryOptions>): UseMutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutMutation = (options?: Partial>): UseMutat export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarOptions = (options?: Options) => queryOptio throwOnError: true }); return data; - }, - queryKey: getFooBarQueryKey(options) + }), + queryKey: getFooBarQueryKey(resolveOptions(options)) }); export const fooBarPostMutation = (options?: Partial>): UseMutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/axios/@tanstack/vue-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/axios/@tanstack/vue-query.gen.ts index 5a5ce3b118..6c3fe37bb3 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/axios/@tanstack/vue-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/axios/@tanstack/vue-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions } from '@tanstack/vue-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; @@ -40,10 +40,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); -export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const serviceWithEmptyTagOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], @@ -51,8 +55,8 @@ export const serviceWithEmptyTagOptions = (options?: Options>): UseMutationOptions, Options> => { @@ -99,8 +103,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -108,8 +112,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): UseMutationOptions, Options> => { @@ -198,8 +202,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -207,8 +211,8 @@ export const callWithDefaultParametersOptions = (options: Options>): UseMutationOptions, Options> => { @@ -255,8 +259,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -264,8 +268,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions, Options> => { @@ -298,8 +302,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -307,14 +311,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -322,14 +326,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -337,14 +341,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -352,14 +356,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -367,8 +371,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { @@ -401,8 +405,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -410,14 +414,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions, TypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -425,14 +429,14 @@ export const typesOptions = (options: Options) => queryOptions) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions, ComplexTypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -440,8 +444,8 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions, Options> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/fetch/@tanstack/vue-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/fetch/@tanstack/vue-query.gen.ts index b545d18172..ea99aaa9cc 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/fetch/@tanstack/vue-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/fetch/@tanstack/vue-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions } from '@tanstack/vue-query'; import { client } from '../client.gen'; import { callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexTypes, deleteCallWithoutParametersAndResponse, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, fooWow, getCallWithoutParametersAndResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionBody, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, serviceWithEmptyTag, testErrorCode, types } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const serviceWithEmptyTagQueryKey = (options?: Options) => createQueryKey('serviceWithEmptyTag', options); -export const serviceWithEmptyTagOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const serviceWithEmptyTagOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await serviceWithEmptyTag({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const serviceWithEmptyTagOptions = (options?: Options>): UseMutationOptions> => { @@ -98,8 +102,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -107,8 +111,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): UseMutationOptions> => { @@ -197,8 +201,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -206,8 +210,8 @@ export const callWithDefaultParametersOptions = (options: Options>): UseMutationOptions> => { @@ -254,8 +258,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -263,8 +267,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { @@ -297,8 +301,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -306,14 +310,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -321,14 +325,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -336,14 +340,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -351,14 +355,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -366,8 +370,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { @@ -400,8 +404,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -409,14 +413,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -424,14 +428,14 @@ export const typesOptions = (options: Options) => queryOptions) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -439,8 +443,8 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/name-builder/@tanstack/vue-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/name-builder/@tanstack/vue-query.gen.ts index bfd35f1d62..3c3f7038e9 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/name-builder/@tanstack/vue-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/2.0.x/plugins/@tanstack/vue-query/name-builder/@tanstack/vue-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions } from '@tanstack/vue-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooD = (options?: Options) => createQueryKey('getFoo', options); -export const getFooE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooE = (options?: Options) => queryOptions>): UseMutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutC = (options?: Partial>): UseMutationOpti export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarE = (options?: Options) => queryOptions>): UseMutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/internal-name-conflict/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/internal-name-conflict/@tanstack/react-query.gen.ts index c7e01dadfe..fd910359e7 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/internal-name-conflict/@tanstack/react-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/internal-name-conflict/@tanstack/react-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/react-query'; import { client } from '../client.gen'; import { create, create2, create3, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const createQueryKey2 = (options?: Options) => createQueryKey('create', options); -export const createOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const createOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await create({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const createOptions = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useCreateQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(createOptions, options); + export const create2Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/asClass/@tanstack/angular-query-experimental.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/asClass/@tanstack/angular-query-experimental.gen.ts index ac5127274b..46e0cb1551 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/asClass/@tanstack/angular-query-experimental.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/asClass/@tanstack/angular-query-experimental.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/angular-query-experimental'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooOptions = (options?: Options) => queryOptions>): MutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutMutation = (options?: Partial>): Mutation export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarOptions = (options?: Options) => queryOptio throwOnError: true }); return data; - }, - queryKey: getFooBarQueryKey(options) + }), + queryKey: getFooBarQueryKey(resolveOptions(options)) }); export const fooBarPostMutation = (options?: Partial>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/axios/@tanstack/angular-query-experimental.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/axios/@tanstack/angular-query-experimental.gen.ts index 5b07cde6a8..8a58ffade5 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/axios/@tanstack/angular-query-experimental.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/axios/@tanstack/angular-query-experimental.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions, skipToken } from '@tanstack/angular-query-experimental'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; @@ -40,10 +40,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -51,8 +55,8 @@ export const exportOptions = (options?: Options) => queryOptions>): MutationOptions, Options> => { @@ -99,8 +103,8 @@ export const fooWowMutation = (options?: Partial>): Mutation export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -108,14 +112,14 @@ export const apiVVersionODataControllerCountOptions = (options?: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -123,8 +127,8 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options>): MutationOptions, Options> => { @@ -143,8 +147,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -152,8 +156,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): MutationOptions, Options> => { @@ -273,8 +277,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -282,8 +286,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -317,10 +321,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -335,8 +339,8 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options>): MutationOptions, Options> => { @@ -383,8 +387,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -392,8 +396,8 @@ export const callWithDefaultParametersOptions = (options?: Options>): MutationOptions, Options> => { @@ -440,8 +444,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -449,8 +453,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions, Options> => { @@ -483,8 +487,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -492,14 +496,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -507,14 +511,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions, DummyAResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -522,14 +526,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions, DummyBResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -537,14 +541,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -552,8 +556,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions, Options> => { @@ -586,8 +590,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -595,14 +599,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions, TypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -610,8 +614,8 @@ export const typesOptions = (options: Options) => queryOptions>): MutationOptions, Options> => { @@ -630,8 +634,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions, FileResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -639,14 +643,14 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions, ComplexTypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -654,14 +658,14 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions, MultipartResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -669,8 +673,8 @@ export const multipartResponseOptions = (options?: Options>): MutationOptions, Options> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/fetch/@tanstack/angular-query-experimental.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/fetch/@tanstack/angular-query-experimental.gen.ts index 6cc80fb17d..d412e3ad70 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/fetch/@tanstack/angular-query-experimental.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/fetch/@tanstack/angular-query-experimental.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions, skipToken } from '@tanstack/angular-query-experimental'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const exportOptions = (options?: Options) => queryOptions>): MutationOptions> => { @@ -98,8 +102,8 @@ export const fooWowMutation = (options?: Partial>): Mutation export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -107,14 +111,14 @@ export const apiVVersionODataControllerCountOptions = (options?: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -122,8 +126,8 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options>): MutationOptions> => { @@ -142,8 +146,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -151,8 +155,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): MutationOptions> => { @@ -272,8 +276,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -281,8 +285,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -316,10 +320,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -334,8 +338,8 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options>): MutationOptions> => { @@ -382,8 +386,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -391,8 +395,8 @@ export const callWithDefaultParametersOptions = (options?: Options>): MutationOptions> => { @@ -439,8 +443,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -448,8 +452,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions> => { @@ -482,8 +486,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -491,14 +495,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -506,14 +510,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -521,14 +525,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -536,14 +540,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -551,8 +555,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions> => { @@ -585,8 +589,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -594,14 +598,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -609,8 +613,8 @@ export const typesOptions = (options: Options) => queryOptions>): MutationOptions> => { @@ -629,8 +633,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -638,14 +642,14 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -653,14 +657,14 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -668,8 +672,8 @@ export const multipartResponseOptions = (options?: Options>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/name-builder/@tanstack/angular-query-experimental.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/name-builder/@tanstack/angular-query-experimental.gen.ts index b144ed7a2c..14938efa33 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/name-builder/@tanstack/angular-query-experimental.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/angular-query-experimental/name-builder/@tanstack/angular-query-experimental.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/angular-query-experimental'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooD = (options?: Options) => createQueryKey('getFoo', options); -export const getFooE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooE = (options?: Options) => queryOptions>): MutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutC = (options?: Partial>): MutationOptions export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarE = (options?: Options) => queryOptions>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/asClass/@tanstack/preact-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/asClass/@tanstack/preact-query.gen.ts index 92fa2c6b00..6e3235ff7f 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/asClass/@tanstack/preact-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/asClass/@tanstack/preact-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/preact-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const getFooOptions = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useGetFooQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooOptions, options); + export const fooPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -84,8 +100,8 @@ export const fooPutMutation = (options?: Partial>): UseMutat export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], @@ -93,10 +109,14 @@ export const getFooBarOptions = (options?: Options) => queryOptio throwOnError: true }); return data; - }, - queryKey: getFooBarQueryKey(options) + }), + queryKey: getFooBarQueryKey(resolveOptions(options)) }); +export const useGetFooBarQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooBarOptions, options); + export const fooBarPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/axios/@tanstack/preact-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/axios/@tanstack/preact-query.gen.ts index 586296750d..2c620a72f3 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/axios/@tanstack/preact-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/axios/@tanstack/preact-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/preact-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; @@ -40,10 +40,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -51,10 +55,22 @@ export const exportOptions = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useExportQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(exportOptions, options); + export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -99,8 +115,8 @@ export const fooWowMutation = (options?: Partial>): UseMutat export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -108,14 +124,18 @@ export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(apiVVersionODataControllerCountOptions, options); + export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -123,10 +143,14 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getApiVbyApiVersionSimpleOperationOptions, options); + export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -143,8 +167,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -152,10 +176,14 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithoutParametersAndResponseOptions, options); + export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -273,8 +301,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -282,8 +310,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -317,10 +345,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -335,10 +363,14 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithOptionalParamOptions, options); + export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -383,8 +415,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -392,10 +424,14 @@ export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithDefaultParametersOptions, options); + export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -440,8 +476,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -449,10 +485,14 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); +export const useDuplicateName2Query = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(duplicateName2Options, options); + export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -483,8 +523,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -492,14 +532,18 @@ export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithNoContentResponseOptions, options); + export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -507,14 +551,18 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseAndNoContentResponseOptions, options); + export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions, DummyAResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -522,14 +570,18 @@ export const dummyAOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyAOptions, options); + export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions, DummyBResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -537,14 +589,18 @@ export const dummyBOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyBOptions, options); + export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -552,10 +608,14 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); +export const useCallWithResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseOptions, options); + export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -586,8 +646,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -595,14 +655,18 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); +export const useCollectionFormatQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(collectionFormatOptions, options); + export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions, TypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -610,10 +674,14 @@ export const typesOptions = (options: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(typesOptions, options); + export const uploadFileMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -630,8 +698,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions, FileResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -639,14 +707,18 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); +export const useFileResponseQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(fileResponseOptions, options); + export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions, ComplexTypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -654,14 +726,18 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); +export const useComplexTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(complexTypesOptions, options); + export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions, MultipartResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -669,10 +745,14 @@ export const multipartResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(multipartResponseOptions, options); + export const multipartRequestMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/fetch/@tanstack/preact-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/fetch/@tanstack/preact-query.gen.ts index 33d1fb83e9..408924a08c 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/fetch/@tanstack/preact-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/fetch/@tanstack/preact-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/preact-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const exportOptions = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useExportQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(exportOptions, options); + export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -98,8 +114,8 @@ export const fooWowMutation = (options?: Partial>): UseMutat export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -107,14 +123,18 @@ export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(apiVVersionODataControllerCountOptions, options); + export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -122,10 +142,14 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getApiVbyApiVersionSimpleOperationOptions, options); + export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -142,8 +166,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -151,10 +175,14 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithoutParametersAndResponseOptions, options); + export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -272,8 +300,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -281,8 +309,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -316,10 +344,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -334,10 +362,14 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithOptionalParamOptions, options); + export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -382,8 +414,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -391,10 +423,14 @@ export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithDefaultParametersOptions, options); + export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -439,8 +475,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -448,10 +484,14 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); +export const useDuplicateName2Query = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(duplicateName2Options, options); + export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -482,8 +522,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -491,14 +531,18 @@ export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithNoContentResponseOptions, options); + export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -506,14 +550,18 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseAndNoContentResponseOptions, options); + export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -521,14 +569,18 @@ export const dummyAOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyAOptions, options); + export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -536,14 +588,18 @@ export const dummyBOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyBOptions, options); + export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -551,10 +607,14 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); +export const useCallWithResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseOptions, options); + export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -585,8 +645,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -594,14 +654,18 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); +export const useCollectionFormatQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(collectionFormatOptions, options); + export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -609,10 +673,14 @@ export const typesOptions = (options: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(typesOptions, options); + export const uploadFileMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -629,8 +697,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -638,14 +706,18 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); +export const useFileResponseQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(fileResponseOptions, options); + export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -653,14 +725,18 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); +export const useComplexTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(complexTypesOptions, options); + export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -668,10 +744,14 @@ export const multipartResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(multipartResponseOptions, options); + export const multipartRequestMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/name-builder/@tanstack/preact-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/name-builder/@tanstack/preact-query.gen.ts index 5552d69766..a363fc4b56 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/name-builder/@tanstack/preact-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/preact-query/name-builder/@tanstack/preact-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/preact-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooD = (options?: Options) => createQueryKey('getFoo', options); -export const getFooE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const getFooE = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useGetFooQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooE, options); + export const fooPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -84,8 +100,8 @@ export const fooPutC = (options?: Partial>): UseMutationOpti export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], @@ -93,10 +109,14 @@ export const getFooBarE = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooBarE, options); + export const fooBarPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/asClass/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/asClass/@tanstack/react-query.gen.ts index 486657ead7..acd235e3f0 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/asClass/@tanstack/react-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/asClass/@tanstack/react-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/react-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const getFooOptions = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useGetFooQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooOptions, options); + export const fooPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -84,8 +100,8 @@ export const fooPutMutation = (options?: Partial>): UseMutat export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], @@ -93,10 +109,14 @@ export const getFooBarOptions = (options?: Options) => queryOptio throwOnError: true }); return data; - }, - queryKey: getFooBarQueryKey(options) + }), + queryKey: getFooBarQueryKey(resolveOptions(options)) }); +export const useGetFooBarQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooBarOptions, options); + export const fooBarPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/axios/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/axios/@tanstack/react-query.gen.ts index 38403265b8..7f34770259 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/axios/@tanstack/react-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/axios/@tanstack/react-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/react-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; @@ -40,10 +40,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -51,10 +55,22 @@ export const exportOptions = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useExportQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(exportOptions, options); + export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -99,8 +115,8 @@ export const fooWowMutation = (options?: Partial>): UseMutat export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -108,14 +124,18 @@ export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(apiVVersionODataControllerCountOptions, options); + export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -123,10 +143,14 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getApiVbyApiVersionSimpleOperationOptions, options); + export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -143,8 +167,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -152,10 +176,14 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithoutParametersAndResponseOptions, options); + export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -273,8 +301,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -282,8 +310,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -317,10 +345,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -335,10 +363,14 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithOptionalParamOptions, options); + export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -383,8 +415,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -392,10 +424,14 @@ export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithDefaultParametersOptions, options); + export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -440,8 +476,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -449,10 +485,14 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); +export const useDuplicateName2Query = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(duplicateName2Options, options); + export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -483,8 +523,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -492,14 +532,18 @@ export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithNoContentResponseOptions, options); + export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -507,14 +551,18 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseAndNoContentResponseOptions, options); + export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions, DummyAResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -522,14 +570,18 @@ export const dummyAOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyAOptions, options); + export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions, DummyBResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -537,14 +589,18 @@ export const dummyBOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyBOptions, options); + export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -552,10 +608,14 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); +export const useCallWithResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseOptions, options); + export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -586,8 +646,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -595,14 +655,18 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); +export const useCollectionFormatQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(collectionFormatOptions, options); + export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions, TypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -610,10 +674,14 @@ export const typesOptions = (options: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(typesOptions, options); + export const uploadFileMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -630,8 +698,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions, FileResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -639,14 +707,18 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); +export const useFileResponseQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(fileResponseOptions, options); + export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions, ComplexTypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -654,14 +726,18 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); +export const useComplexTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(complexTypesOptions, options); + export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions, MultipartResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -669,10 +745,14 @@ export const multipartResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(multipartResponseOptions, options); + export const multipartRequestMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/fetch/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/fetch/@tanstack/react-query.gen.ts index 378082bd09..b942d5c500 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/fetch/@tanstack/react-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/fetch/@tanstack/react-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/react-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const exportOptions = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useExportQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(exportOptions, options); + export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -98,8 +114,8 @@ export const fooWowMutation = (options?: Partial>): UseMutat export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -107,14 +123,18 @@ export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(apiVVersionODataControllerCountOptions, options); + export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -122,10 +142,14 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getApiVbyApiVersionSimpleOperationOptions, options); + export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -142,8 +166,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -151,10 +175,14 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithoutParametersAndResponseOptions, options); + export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -272,8 +300,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -281,8 +309,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -316,10 +344,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -334,10 +362,14 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithOptionalParamOptions, options); + export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -382,8 +414,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -391,10 +423,14 @@ export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithDefaultParametersOptions, options); + export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -439,8 +475,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -448,10 +484,14 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); +export const useDuplicateName2Query = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(duplicateName2Options, options); + export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -482,8 +522,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -491,14 +531,18 @@ export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithNoContentResponseOptions, options); + export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -506,14 +550,18 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseAndNoContentResponseOptions, options); + export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -521,14 +569,18 @@ export const dummyAOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyAOptions, options); + export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -536,14 +588,18 @@ export const dummyBOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyBOptions, options); + export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -551,10 +607,14 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); +export const useCallWithResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseOptions, options); + export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -585,8 +645,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -594,14 +654,18 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); +export const useCollectionFormatQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(collectionFormatOptions, options); + export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -609,10 +673,14 @@ export const typesOptions = (options: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(typesOptions, options); + export const uploadFileMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -629,8 +697,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -638,14 +706,18 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); +export const useFileResponseQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(fileResponseOptions, options); + export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -653,14 +725,18 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); +export const useComplexTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(complexTypesOptions, options); + export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -668,10 +744,14 @@ export const multipartResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(multipartResponseOptions, options); + export const multipartRequestMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/name-builder/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/name-builder/@tanstack/react-query.gen.ts index 43c90277c2..34df178948 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/name-builder/@tanstack/react-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/name-builder/@tanstack/react-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/react-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooD = (options?: Options) => createQueryKey('getFoo', options); -export const getFooE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const getFooE = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useGetFooQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooE, options); + export const fooPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -84,8 +100,8 @@ export const fooPutC = (options?: Partial>): UseMutationOpti export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], @@ -93,10 +109,14 @@ export const getFooBarE = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooBarE, options); + export const fooBarPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/@tanstack/react-query.gen.ts new file mode 100644 index 0000000000..40c8901183 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/@tanstack/react-query.gen.ts @@ -0,0 +1,840 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/react-query'; + +import { client } from '../client.gen'; +import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; +import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; + +export type QueryKey = [ + Pick & { + _id: string; + _infinite?: boolean; + tags?: ReadonlyArray; + } +]; + +const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ + QueryKey[0] +] => { + const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; + if (infinite) { + params._infinite = infinite; + } + if (tags) { + params.tags = tags; + } + if (options?.body) { + params.body = options.body; + } + if (options?.headers) { + params.headers = options.headers; + } + if (options?.path) { + params.path = options.path; + } + if (options?.query) { + params.query = options.query; + } + return [params]; +}; + +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + +export const exportQueryKey = (options?: Options) => createQueryKey('export', options); + +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await export_({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: exportQueryKey(resolveOptions(options)) +}); + +const queryWithOptions = (optionsFn: Function, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useExportQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(exportOptions, options); + +export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await patchApiVbyApiVersionNoTag({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const importMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await import_({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const fooWowMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await fooWow({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); + +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await apiVVersionODataControllerCount({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: apiVVersionODataControllerCountQueryKey(resolveOptions(options)) +}); + +export const useApiVVersionODataControllerCountQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(apiVVersionODataControllerCountOptions, options); + +export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); + +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await getApiVbyApiVersionSimpleOperation({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: getApiVbyApiVersionSimpleOperationQueryKey(resolveOptions(options)) +}); + +export const useGetApiVbyApiVersionSimpleOperationQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getApiVbyApiVersionSimpleOperationOptions, options); + +export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deleteCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); + +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await getCallWithoutParametersAndResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: getCallWithoutParametersAndResponseQueryKey(resolveOptions(options)) +}); + +export const useGetCallWithoutParametersAndResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithoutParametersAndResponseOptions, options); + +export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await patchCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await putCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const deleteFooMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deleteFoo({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDescriptions({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * @deprecated + */ +export const deprecatedCallMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deprecatedCall({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithParametersMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithParameters({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithWeirdParameterNames({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); + +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await getCallWithOptionalParam({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: getCallWithOptionalParamQueryKey(resolveOptions(options)) +}); + +const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { + const params = { ...queryKey[0] }; + if (page.body) { + params.body = { + ...queryKey[0].body as any, + ...page.body as any + }; + } + if (page.headers) { + params.headers = { + ...queryKey[0].headers, + ...page.headers + }; + } + if (page.path) { + params.path = { + ...queryKey[0].path as any, + ...page.path as any + }; + } + if (page.query) { + params.query = { + ...queryKey[0].query as any, + ...page.query as any + }; + } + return params as unknown as typeof page; +}; + +export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); + +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +// @ts-ignore +{ + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { + // @ts-ignore + const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { + query: { + page: pageParam + } + }; + const params = createInfiniteParams(queryKey, page); + const { data } = await getCallWithOptionalParam({ + ...options, + ...params, + signal, + throwOnError: true + }); + return data; + }), + queryKey: getCallWithOptionalParamInfiniteQueryKey(resolveOptions(options)) +}); + +export const useGetCallWithOptionalParamQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithOptionalParamOptions, options); + +export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postCallWithOptionalParam({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postApiVbyApiVersionRequestBody({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postApiVbyApiVersionFormData({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); + +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithDefaultParameters({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithDefaultParametersQueryKey(resolveOptions(options)) +}); + +export const useCallWithDefaultParametersQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithDefaultParametersOptions, options); + +export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDefaultOptionalParameters({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callToTestOrderOfParams({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateNameMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); + +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await duplicateName2({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) +}); + +export const useDuplicateName2Query = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(duplicateName2Options, options); + +export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName3({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName4({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); + +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithNoContentResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithNoContentResponseQueryKey(resolveOptions(options)) +}); + +export const useCallWithNoContentResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithNoContentResponseOptions, options); + +export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); + +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithResponseAndNoContentResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithResponseAndNoContentResponseQueryKey(resolveOptions(options)) +}); + +export const useCallWithResponseAndNoContentResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseAndNoContentResponseOptions, options); + +export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); + +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await dummyA({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: dummyAQueryKey(resolveOptions(options)) +}); + +export const useDummyAQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyAOptions, options); + +export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); + +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await dummyB({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: dummyBQueryKey(resolveOptions(options)) +}); + +export const useDummyBQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyBOptions, options); + +export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); + +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) +}); + +export const useCallWithResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseOptions, options); + +export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDuplicateResponses({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithResponses({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); + +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await collectionFormat({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) +}); + +export const useCollectionFormatQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(collectionFormatOptions, options); + +export const typesQueryKey = (options: Options) => createQueryKey('types', options); + +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await types({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: typesQueryKey(resolveOptions(options)) +}); + +export const useTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(typesOptions, options); + +export const uploadFileMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await uploadFile({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); + +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await fileResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) +}); + +export const useFileResponseQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(fileResponseOptions, options); + +export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); + +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await complexTypes({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) +}); + +export const useComplexTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(complexTypesOptions, options); + +export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); + +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await multipartResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: multipartResponseQueryKey(resolveOptions(options)) +}); + +export const useMultipartResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(multipartResponseOptions, options); + +export const multipartRequestMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await multipartRequest({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const complexParamsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await complexParams({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithResultFromHeader({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await testErrorCode({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * Login User + */ +export const putWithFormUrlEncodedMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await putWithFormUrlEncoded({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/client.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/client.gen.ts new file mode 100644 index 0000000000..25cd14eafb --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/client.gen.ts @@ -0,0 +1,16 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type ClientOptions, type Config, createClient, createConfig } from './client'; +import type { ClientOptions as ClientOptions2 } from './types.gen'; + +/** + * The `createClientConfig()` function will be called on client initialization + * and the returned object will become the client's initial configuration. + * + * You may want to initialize your client this way instead of calling + * `setConfig()`. This is useful for example if you're using Next.js + * to ensure your client always has the correct values. + */ +export type CreateClientConfig = (override?: Config) => Config & T>; + +export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/client/client.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/client/client.gen.ts new file mode 100644 index 0000000000..14dc0a0ec5 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/client/client.gen.ts @@ -0,0 +1,290 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { createSseClient } from '../core/serverSentEvents.gen'; +import type { HttpMethod } from '../core/types.gen'; +import { getValidRequestBody } from '../core/utils.gen'; +import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; +import { + buildUrl, + createConfig, + createInterceptors, + getParseAs, + mergeConfigs, + mergeHeaders, + setAuthParams, +} from './utils.gen'; + +type ReqInit = Omit & { + body?: any; + headers: ReturnType; +}; + +export const createClient = (config: Config = {}): Client => { + let _config = mergeConfigs(createConfig(), config); + + const getConfig = (): Config => ({ ..._config }); + + const setConfig = (config: Config): Config => { + _config = mergeConfigs(_config, config); + return getConfig(); + }; + + const interceptors = createInterceptors(); + + const beforeRequest = async (options: RequestOptions) => { + const opts = { + ..._config, + ...options, + fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, + headers: mergeHeaders(_config.headers, options.headers), + serializedBody: undefined as string | undefined, + }; + + if (opts.security) { + await setAuthParams({ + ...opts, + security: opts.security, + }); + } + + if (opts.requestValidator) { + await opts.requestValidator(opts); + } + + if (opts.body !== undefined && opts.bodySerializer) { + opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; + } + + // remove Content-Type header if body is empty to avoid sending invalid requests + if (opts.body === undefined || opts.serializedBody === '') { + opts.headers.delete('Content-Type'); + } + + const url = buildUrl(opts); + + return { opts, url }; + }; + + const request: Client['request'] = async (options) => { + // @ts-expect-error + const { opts, url } = await beforeRequest(options); + const requestInit: ReqInit = { + redirect: 'follow', + ...opts, + body: getValidRequestBody(opts), + }; + + let request = new Request(url, requestInit); + + for (const fn of interceptors.request.fns) { + if (fn) { + request = await fn(request, opts); + } + } + + // fetch must be assigned here, otherwise it would throw the error: + // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation + const _fetch = opts.fetch!; + let response: Response; + + try { + response = await _fetch(request); + } catch (error) { + // Handle fetch exceptions (AbortError, network errors, etc.) + let finalError = error; + + for (const fn of interceptors.error.fns) { + if (fn) { + finalError = (await fn(error, undefined as any, request, opts)) as unknown; + } + } + + finalError = finalError || ({} as unknown); + + if (opts.throwOnError) { + throw finalError; + } + + // Return error response + return opts.responseStyle === 'data' + ? undefined + : { + error: finalError, + request, + response: undefined as any, + }; + } + + for (const fn of interceptors.response.fns) { + if (fn) { + response = await fn(response, request, opts); + } + } + + const result = { + request, + response, + }; + + if (response.ok) { + const parseAs = + (opts.parseAs === 'auto' + ? getParseAs(response.headers.get('Content-Type')) + : opts.parseAs) ?? 'json'; + + if (response.status === 204 || response.headers.get('Content-Length') === '0') { + let emptyData: any; + switch (parseAs) { + case 'arrayBuffer': + case 'blob': + case 'text': + emptyData = await response[parseAs](); + break; + case 'formData': + emptyData = new FormData(); + break; + case 'stream': + emptyData = response.body; + break; + case 'json': + default: + emptyData = {}; + break; + } + return opts.responseStyle === 'data' + ? emptyData + : { + data: emptyData, + ...result, + }; + } + + let data: any; + switch (parseAs) { + case 'arrayBuffer': + case 'blob': + case 'formData': + case 'text': + data = await response[parseAs](); + break; + case 'json': { + // Some servers return 200 with no Content-Length and empty body. + // response.json() would throw; read as text and parse if non-empty. + const text = await response.text(); + data = text ? JSON.parse(text) : {}; + break; + } + case 'stream': + return opts.responseStyle === 'data' + ? response.body + : { + data: response.body, + ...result, + }; + } + + if (parseAs === 'json') { + if (opts.responseValidator) { + await opts.responseValidator(data); + } + + if (opts.responseTransformer) { + data = await opts.responseTransformer(data); + } + } + + return opts.responseStyle === 'data' + ? data + : { + data, + ...result, + }; + } + + const textError = await response.text(); + let jsonError: unknown; + + try { + jsonError = JSON.parse(textError); + } catch { + // noop + } + + const error = jsonError ?? textError; + let finalError = error; + + for (const fn of interceptors.error.fns) { + if (fn) { + finalError = (await fn(error, response, request, opts)) as string; + } + } + + finalError = finalError || ({} as string); + + if (opts.throwOnError) { + throw finalError; + } + + // TODO: we probably want to return error and improve types + return opts.responseStyle === 'data' + ? undefined + : { + error: finalError, + ...result, + }; + }; + + const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => + request({ ...options, method }); + + const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { + const { opts, url } = await beforeRequest(options); + return createSseClient({ + ...opts, + body: opts.body as BodyInit | null | undefined, + headers: opts.headers as unknown as Record, + method, + onRequest: async (url, init) => { + let request = new Request(url, init); + for (const fn of interceptors.request.fns) { + if (fn) { + request = await fn(request, opts); + } + } + return request; + }, + serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, + url, + }); + }; + + const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); + + return { + buildUrl: _buildUrl, + connect: makeMethodFn('CONNECT'), + delete: makeMethodFn('DELETE'), + get: makeMethodFn('GET'), + getConfig, + head: makeMethodFn('HEAD'), + interceptors, + options: makeMethodFn('OPTIONS'), + patch: makeMethodFn('PATCH'), + post: makeMethodFn('POST'), + put: makeMethodFn('PUT'), + request, + setConfig, + sse: { + connect: makeSseFn('CONNECT'), + delete: makeSseFn('DELETE'), + get: makeSseFn('GET'), + head: makeSseFn('HEAD'), + options: makeSseFn('OPTIONS'), + patch: makeSseFn('PATCH'), + post: makeSseFn('POST'), + put: makeSseFn('PUT'), + trace: makeSseFn('TRACE'), + }, + trace: makeMethodFn('TRACE'), + } as Client; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/client/index.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/client/index.ts new file mode 100644 index 0000000000..b295edeca0 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/client/index.ts @@ -0,0 +1,25 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type { Auth } from '../core/auth.gen'; +export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; +export { + formDataBodySerializer, + jsonBodySerializer, + urlSearchParamsBodySerializer, +} from '../core/bodySerializer.gen'; +export { buildClientParams } from '../core/params.gen'; +export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; +export { createClient } from './client.gen'; +export type { + Client, + ClientOptions, + Config, + CreateClientConfig, + Options, + RequestOptions, + RequestResult, + ResolvedRequestOptions, + ResponseStyle, + TDataShape, +} from './types.gen'; +export { createConfig, mergeHeaders } from './utils.gen'; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/client/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/client/types.gen.ts new file mode 100644 index 0000000000..a3f8616511 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/client/types.gen.ts @@ -0,0 +1,214 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Auth } from '../core/auth.gen'; +import type { + ServerSentEventsOptions, + ServerSentEventsResult, +} from '../core/serverSentEvents.gen'; +import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; +import type { Middleware } from './utils.gen'; + +export type ResponseStyle = 'data' | 'fields'; + +export interface Config + extends Omit, CoreConfig { + /** + * Base URL for all requests made by this client. + */ + baseUrl?: T['baseUrl']; + /** + * Fetch API implementation. You can use this option to provide a custom + * fetch instance. + * + * @default globalThis.fetch + */ + fetch?: typeof fetch; + /** + * Please don't use the Fetch client for Next.js applications. The `next` + * options won't have any effect. + * + * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. + */ + next?: never; + /** + * Return the response data parsed in a specified format. By default, `auto` + * will infer the appropriate method from the `Content-Type` response header. + * You can override this behavior with any of the {@link Body} methods. + * Select `stream` if you don't want to parse response data at all. + * + * @default 'auto' + */ + parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; + /** + * Should we return only data or multiple fields (data, error, response, etc.)? + * + * @default 'fields' + */ + responseStyle?: ResponseStyle; + /** + * Throw an error instead of returning it in the response? + * + * @default false + */ + throwOnError?: T['throwOnError']; +} + +export interface RequestOptions< + TData = unknown, + TResponseStyle extends ResponseStyle = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, +> + extends + Config<{ + responseStyle: TResponseStyle; + throwOnError: ThrowOnError; + }>, + Pick< + ServerSentEventsOptions, + | 'onRequest' + | 'onSseError' + | 'onSseEvent' + | 'sseDefaultRetryDelay' + | 'sseMaxRetryAttempts' + | 'sseMaxRetryDelay' + > { + /** + * Any body that you want to add to your request. + * + * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} + */ + body?: unknown; + path?: Record; + query?: Record; + /** + * Security mechanism(s) to use for the request. + */ + security?: ReadonlyArray; + url: Url; +} + +export interface ResolvedRequestOptions< + TResponseStyle extends ResponseStyle = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, +> extends RequestOptions { + serializedBody?: string; +} + +export type RequestResult< + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = boolean, + TResponseStyle extends ResponseStyle = 'fields', +> = ThrowOnError extends true + ? Promise< + TResponseStyle extends 'data' + ? TData extends Record + ? TData[keyof TData] + : TData + : { + data: TData extends Record ? TData[keyof TData] : TData; + request: Request; + response: Response; + } + > + : Promise< + TResponseStyle extends 'data' + ? (TData extends Record ? TData[keyof TData] : TData) | undefined + : ( + | { + data: TData extends Record ? TData[keyof TData] : TData; + error: undefined; + } + | { + data: undefined; + error: TError extends Record ? TError[keyof TError] : TError; + } + ) & { + request: Request; + response: Response; + } + >; + +export interface ClientOptions { + baseUrl?: string; + responseStyle?: ResponseStyle; + throwOnError?: boolean; +} + +type MethodFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'>, +) => RequestResult; + +type SseFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'>, +) => Promise>; + +type RequestFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'> & + Pick>, 'method'>, +) => RequestResult; + +type BuildUrlFn = < + TData extends { + body?: unknown; + path?: Record; + query?: Record; + url: string; + }, +>( + options: TData & Options, +) => string; + +export type Client = CoreClient & { + interceptors: Middleware; +}; + +/** + * The `createClientConfig()` function will be called on client initialization + * and the returned object will become the client's initial configuration. + * + * You may want to initialize your client this way instead of calling + * `setConfig()`. This is useful for example if you're using Next.js + * to ensure your client always has the correct values. + */ +export type CreateClientConfig = ( + override?: Config, +) => Config & T>; + +export interface TDataShape { + body?: unknown; + headers?: unknown; + path?: unknown; + query?: unknown; + url: string; +} + +type OmitKeys = Pick>; + +export type Options< + TData extends TDataShape = TDataShape, + ThrowOnError extends boolean = boolean, + TResponse = unknown, + TResponseStyle extends ResponseStyle = 'fields', +> = OmitKeys< + RequestOptions, + 'body' | 'path' | 'query' | 'url' +> & + ([TData] extends [never] ? unknown : Omit); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/client/utils.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/client/utils.gen.ts new file mode 100644 index 0000000000..b4bd2435ce --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/client/utils.gen.ts @@ -0,0 +1,316 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { getAuthToken } from '../core/auth.gen'; +import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; +import { jsonBodySerializer } from '../core/bodySerializer.gen'; +import { + serializeArrayParam, + serializeObjectParam, + serializePrimitiveParam, +} from '../core/pathSerializer.gen'; +import { getUrl } from '../core/utils.gen'; +import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; + +export const createQuerySerializer = ({ + parameters = {}, + ...args +}: QuerySerializerOptions = {}) => { + const querySerializer = (queryParams: T) => { + const search: string[] = []; + if (queryParams && typeof queryParams === 'object') { + for (const name in queryParams) { + const value = queryParams[name]; + + if (value === undefined || value === null) { + continue; + } + + const options = parameters[name] || args; + + if (Array.isArray(value)) { + const serializedArray = serializeArrayParam({ + allowReserved: options.allowReserved, + explode: true, + name, + style: 'form', + value, + ...options.array, + }); + if (serializedArray) search.push(serializedArray); + } else if (typeof value === 'object') { + const serializedObject = serializeObjectParam({ + allowReserved: options.allowReserved, + explode: true, + name, + style: 'deepObject', + value: value as Record, + ...options.object, + }); + if (serializedObject) search.push(serializedObject); + } else { + const serializedPrimitive = serializePrimitiveParam({ + allowReserved: options.allowReserved, + name, + value: value as string, + }); + if (serializedPrimitive) search.push(serializedPrimitive); + } + } + } + return search.join('&'); + }; + return querySerializer; +}; + +/** + * Infers parseAs value from provided Content-Type header. + */ +export const getParseAs = (contentType: string | null): Exclude => { + if (!contentType) { + // If no Content-Type header is provided, the best we can do is return the raw response body, + // which is effectively the same as the 'stream' option. + return 'stream'; + } + + const cleanContent = contentType.split(';')[0]?.trim(); + + if (!cleanContent) { + return; + } + + if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { + return 'json'; + } + + if (cleanContent === 'multipart/form-data') { + return 'formData'; + } + + if ( + ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) + ) { + return 'blob'; + } + + if (cleanContent.startsWith('text/')) { + return 'text'; + } + + return; +}; + +const checkForExistence = ( + options: Pick & { + headers: Headers; + }, + name?: string, +): boolean => { + if (!name) { + return false; + } + if ( + options.headers.has(name) || + options.query?.[name] || + options.headers.get('Cookie')?.includes(`${name}=`) + ) { + return true; + } + return false; +}; + +export const setAuthParams = async ({ + security, + ...options +}: Pick, 'security'> & + Pick & { + headers: Headers; + }) => { + for (const auth of security) { + if (checkForExistence(options, auth.name)) { + continue; + } + + const token = await getAuthToken(auth, options.auth); + + if (!token) { + continue; + } + + const name = auth.name ?? 'Authorization'; + + switch (auth.in) { + case 'query': + if (!options.query) { + options.query = {}; + } + options.query[name] = token; + break; + case 'cookie': + options.headers.append('Cookie', `${name}=${token}`); + break; + case 'header': + default: + options.headers.set(name, token); + break; + } + } +}; + +export const buildUrl: Client['buildUrl'] = (options) => + getUrl({ + baseUrl: options.baseUrl as string, + path: options.path, + query: options.query, + querySerializer: + typeof options.querySerializer === 'function' + ? options.querySerializer + : createQuerySerializer(options.querySerializer), + url: options.url, + }); + +export const mergeConfigs = (a: Config, b: Config): Config => { + const config = { ...a, ...b }; + if (config.baseUrl?.endsWith('/')) { + config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); + } + config.headers = mergeHeaders(a.headers, b.headers); + return config; +}; + +const headersEntries = (headers: Headers): Array<[string, string]> => { + const entries: Array<[string, string]> = []; + headers.forEach((value, key) => { + entries.push([key, value]); + }); + return entries; +}; + +export const mergeHeaders = ( + ...headers: Array['headers'] | undefined> +): Headers => { + const mergedHeaders = new Headers(); + for (const header of headers) { + if (!header) { + continue; + } + + const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); + + for (const [key, value] of iterator) { + if (value === null) { + mergedHeaders.delete(key); + } else if (Array.isArray(value)) { + for (const v of value) { + mergedHeaders.append(key, v as string); + } + } else if (value !== undefined) { + // assume object headers are meant to be JSON stringified, i.e. their + // content value in OpenAPI specification is 'application/json' + mergedHeaders.set( + key, + typeof value === 'object' ? JSON.stringify(value) : (value as string), + ); + } + } + } + return mergedHeaders; +}; + +type ErrInterceptor = ( + error: Err, + response: Res, + request: Req, + options: Options, +) => Err | Promise; + +type ReqInterceptor = (request: Req, options: Options) => Req | Promise; + +type ResInterceptor = ( + response: Res, + request: Req, + options: Options, +) => Res | Promise; + +class Interceptors { + fns: Array = []; + + clear(): void { + this.fns = []; + } + + eject(id: number | Interceptor): void { + const index = this.getInterceptorIndex(id); + if (this.fns[index]) { + this.fns[index] = null; + } + } + + exists(id: number | Interceptor): boolean { + const index = this.getInterceptorIndex(id); + return Boolean(this.fns[index]); + } + + getInterceptorIndex(id: number | Interceptor): number { + if (typeof id === 'number') { + return this.fns[id] ? id : -1; + } + return this.fns.indexOf(id); + } + + update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { + const index = this.getInterceptorIndex(id); + if (this.fns[index]) { + this.fns[index] = fn; + return id; + } + return false; + } + + use(fn: Interceptor): number { + this.fns.push(fn); + return this.fns.length - 1; + } +} + +export interface Middleware { + error: Interceptors>; + request: Interceptors>; + response: Interceptors>; +} + +export const createInterceptors = (): Middleware< + Req, + Res, + Err, + Options +> => ({ + error: new Interceptors>(), + request: new Interceptors>(), + response: new Interceptors>(), +}); + +const defaultQuerySerializer = createQuerySerializer({ + allowReserved: false, + array: { + explode: true, + style: 'form', + }, + object: { + explode: true, + style: 'deepObject', + }, +}); + +const defaultHeaders = { + 'Content-Type': 'application/json', +}; + +export const createConfig = ( + override: Config & T> = {}, +): Config & T> => ({ + ...jsonBodySerializer, + headers: defaultHeaders, + parseAs: 'auto', + querySerializer: defaultQuerySerializer, + ...override, +}); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/auth.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/auth.gen.ts new file mode 100644 index 0000000000..3ebf994788 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/auth.gen.ts @@ -0,0 +1,41 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type AuthToken = string | undefined; + +export interface Auth { + /** + * Which part of the request do we use to send the auth? + * + * @default 'header' + */ + in?: 'header' | 'query' | 'cookie'; + /** + * Header or query parameter name. + * + * @default 'Authorization' + */ + name?: string; + scheme?: 'basic' | 'bearer'; + type: 'apiKey' | 'http'; +} + +export const getAuthToken = async ( + auth: Auth, + callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, +): Promise => { + const token = typeof callback === 'function' ? await callback(auth) : callback; + + if (!token) { + return; + } + + if (auth.scheme === 'bearer') { + return `Bearer ${token}`; + } + + if (auth.scheme === 'basic') { + return `Basic ${btoa(token)}`; + } + + return token; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/bodySerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/bodySerializer.gen.ts new file mode 100644 index 0000000000..67daca60f8 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/bodySerializer.gen.ts @@ -0,0 +1,82 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; + +export type QuerySerializer = (query: Record) => string; + +export type BodySerializer = (body: unknown) => unknown; + +type QuerySerializerOptionsObject = { + allowReserved?: boolean; + array?: Partial>; + object?: Partial>; +}; + +export type QuerySerializerOptions = QuerySerializerOptionsObject & { + /** + * Per-parameter serialization overrides. When provided, these settings + * override the global array/object settings for specific parameter names. + */ + parameters?: Record; +}; + +const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { + if (typeof value === 'string' || value instanceof Blob) { + data.append(key, value); + } else if (value instanceof Date) { + data.append(key, value.toISOString()); + } else { + data.append(key, JSON.stringify(value)); + } +}; + +const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { + if (typeof value === 'string') { + data.append(key, value); + } else { + data.append(key, JSON.stringify(value)); + } +}; + +export const formDataBodySerializer = { + bodySerializer: (body: unknown): FormData => { + const data = new FormData(); + + Object.entries(body as Record).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + if (Array.isArray(value)) { + value.forEach((v) => serializeFormDataPair(data, key, v)); + } else { + serializeFormDataPair(data, key, value); + } + }); + + return data; + }, +}; + +export const jsonBodySerializer = { + bodySerializer: (body: unknown): string => + JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), +}; + +export const urlSearchParamsBodySerializer = { + bodySerializer: (body: unknown): string => { + const data = new URLSearchParams(); + + Object.entries(body as Record).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + if (Array.isArray(value)) { + value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); + } else { + serializeUrlSearchParamsPair(data, key, value); + } + }); + + return data.toString(); + }, +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/params.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/params.gen.ts new file mode 100644 index 0000000000..7955601a5c --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/params.gen.ts @@ -0,0 +1,169 @@ +// This file is auto-generated by @hey-api/openapi-ts + +type Slot = 'body' | 'headers' | 'path' | 'query'; + +export type Field = + | { + in: Exclude; + /** + * Field name. This is the name we want the user to see and use. + */ + key: string; + /** + * Field mapped name. This is the name we want to use in the request. + * If omitted, we use the same value as `key`. + */ + map?: string; + } + | { + in: Extract; + /** + * Key isn't required for bodies. + */ + key?: string; + map?: string; + } + | { + /** + * Field name. This is the name we want the user to see and use. + */ + key: string; + /** + * Field mapped name. This is the name we want to use in the request. + * If `in` is omitted, `map` aliases `key` to the transport layer. + */ + map: Slot; + }; + +export interface Fields { + allowExtra?: Partial>; + args?: ReadonlyArray; +} + +export type FieldsConfig = ReadonlyArray; + +const extraPrefixesMap: Record = { + $body_: 'body', + $headers_: 'headers', + $path_: 'path', + $query_: 'query', +}; +const extraPrefixes = Object.entries(extraPrefixesMap); + +type KeyMap = Map< + string, + | { + in: Slot; + map?: string; + } + | { + in?: never; + map: Slot; + } +>; + +const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { + if (!map) { + map = new Map(); + } + + for (const config of fields) { + if ('in' in config) { + if (config.key) { + map.set(config.key, { + in: config.in, + map: config.map, + }); + } + } else if ('key' in config) { + map.set(config.key, { + map: config.map, + }); + } else if (config.args) { + buildKeyMap(config.args, map); + } + } + + return map; +}; + +interface Params { + body: unknown; + headers: Record; + path: Record; + query: Record; +} + +const stripEmptySlots = (params: Params) => { + for (const [slot, value] of Object.entries(params)) { + if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { + delete params[slot as Slot]; + } + } +}; + +export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { + const params: Params = { + body: {}, + headers: {}, + path: {}, + query: {}, + }; + + const map = buildKeyMap(fields); + + let config: FieldsConfig[number] | undefined; + + for (const [index, arg] of args.entries()) { + if (fields[index]) { + config = fields[index]; + } + + if (!config) { + continue; + } + + if ('in' in config) { + if (config.key) { + const field = map.get(config.key)!; + const name = field.map || config.key; + if (field.in) { + (params[field.in] as Record)[name] = arg; + } + } else { + params.body = arg; + } + } else { + for (const [key, value] of Object.entries(arg ?? {})) { + const field = map.get(key); + + if (field) { + if (field.in) { + const name = field.map || key; + (params[field.in] as Record)[name] = value; + } else { + params[field.map] = value; + } + } else { + const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); + + if (extra) { + const [prefix, slot] = extra; + (params[slot] as Record)[key.slice(prefix.length)] = value; + } else if ('allowExtra' in config && config.allowExtra) { + for (const [slot, allowed] of Object.entries(config.allowExtra)) { + if (allowed) { + (params[slot as Slot] as Record)[key] = value; + break; + } + } + } + } + } + } + } + + stripEmptySlots(params); + + return params; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/pathSerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/pathSerializer.gen.ts new file mode 100644 index 0000000000..994b2848c6 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/pathSerializer.gen.ts @@ -0,0 +1,171 @@ +// This file is auto-generated by @hey-api/openapi-ts + +interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} + +interface SerializePrimitiveOptions { + allowReserved?: boolean; + name: string; +} + +export interface SerializerOptions { + /** + * @default true + */ + explode: boolean; + style: T; +} + +export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; +export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; +type MatrixStyle = 'label' | 'matrix' | 'simple'; +export type ObjectStyle = 'form' | 'deepObject'; +type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; + +interface SerializePrimitiveParam extends SerializePrimitiveOptions { + value: string; +} + +export const separatorArrayExplode = (style: ArraySeparatorStyle) => { + switch (style) { + case 'label': + return '.'; + case 'matrix': + return ';'; + case 'simple': + return ','; + default: + return '&'; + } +}; + +export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { + switch (style) { + case 'form': + return ','; + case 'pipeDelimited': + return '|'; + case 'spaceDelimited': + return '%20'; + default: + return ','; + } +}; + +export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { + switch (style) { + case 'label': + return '.'; + case 'matrix': + return ';'; + case 'simple': + return ','; + default: + return '&'; + } +}; + +export const serializeArrayParam = ({ + allowReserved, + explode, + name, + style, + value, +}: SerializeOptions & { + value: unknown[]; +}) => { + if (!explode) { + const joinedValues = ( + allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) + ).join(separatorArrayNoExplode(style)); + switch (style) { + case 'label': + return `.${joinedValues}`; + case 'matrix': + return `;${name}=${joinedValues}`; + case 'simple': + return joinedValues; + default: + return `${name}=${joinedValues}`; + } + } + + const separator = separatorArrayExplode(style); + const joinedValues = value + .map((v) => { + if (style === 'label' || style === 'simple') { + return allowReserved ? v : encodeURIComponent(v as string); + } + + return serializePrimitiveParam({ + allowReserved, + name, + value: v as string, + }); + }) + .join(separator); + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; +}; + +export const serializePrimitiveParam = ({ + allowReserved, + name, + value, +}: SerializePrimitiveParam) => { + if (value === undefined || value === null) { + return ''; + } + + if (typeof value === 'object') { + throw new Error( + 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', + ); + } + + return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; +}; + +export const serializeObjectParam = ({ + allowReserved, + explode, + name, + style, + value, + valueOnly, +}: SerializeOptions & { + value: Record | Date; + valueOnly?: boolean; +}) => { + if (value instanceof Date) { + return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; + } + + if (style !== 'deepObject' && !explode) { + let values: string[] = []; + Object.entries(value).forEach(([key, v]) => { + values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; + }); + const joinedValues = values.join(','); + switch (style) { + case 'form': + return `${name}=${joinedValues}`; + case 'label': + return `.${joinedValues}`; + case 'matrix': + return `;${name}=${joinedValues}`; + default: + return joinedValues; + } + } + + const separator = separatorObjectExplode(style); + const joinedValues = Object.entries(value) + .map(([key, v]) => + serializePrimitiveParam({ + allowReserved, + name: style === 'deepObject' ? `${name}[${key}]` : key, + value: v as string, + }), + ) + .join(separator); + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/queryKeySerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/queryKeySerializer.gen.ts new file mode 100644 index 0000000000..5000df606f --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/queryKeySerializer.gen.ts @@ -0,0 +1,117 @@ +// This file is auto-generated by @hey-api/openapi-ts + +/** + * JSON-friendly union that mirrors what Pinia Colada can hash. + */ +export type JsonValue = + | null + | string + | number + | boolean + | JsonValue[] + | { [key: string]: JsonValue }; + +/** + * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. + */ +export const queryKeyJsonReplacer = (_key: string, value: unknown) => { + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { + return undefined; + } + if (typeof value === 'bigint') { + return value.toString(); + } + if (value instanceof Date) { + return value.toISOString(); + } + return value; +}; + +/** + * Safely stringifies a value and parses it back into a JsonValue. + */ +export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { + try { + const json = JSON.stringify(input, queryKeyJsonReplacer); + if (json === undefined) { + return undefined; + } + return JSON.parse(json) as JsonValue; + } catch { + return undefined; + } +}; + +/** + * Detects plain objects (including objects with a null prototype). + */ +const isPlainObject = (value: unknown): value is Record => { + if (value === null || typeof value !== 'object') { + return false; + } + const prototype = Object.getPrototypeOf(value as object); + return prototype === Object.prototype || prototype === null; +}; + +/** + * Turns URLSearchParams into a sorted JSON object for deterministic keys. + */ +const serializeSearchParams = (params: URLSearchParams): JsonValue => { + const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); + const result: Record = {}; + + for (const [key, value] of entries) { + const existing = result[key]; + if (existing === undefined) { + result[key] = value; + continue; + } + + if (Array.isArray(existing)) { + (existing as string[]).push(value); + } else { + result[key] = [existing, value]; + } + } + + return result; +}; + +/** + * Normalizes any accepted value into a JSON-friendly shape for query keys. + */ +export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { + if (value === null) { + return null; + } + + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return value; + } + + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { + return undefined; + } + + if (typeof value === 'bigint') { + return value.toString(); + } + + if (value instanceof Date) { + return value.toISOString(); + } + + if (Array.isArray(value)) { + return stringifyToJsonValue(value); + } + + if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { + return serializeSearchParams(value); + } + + if (isPlainObject(value)) { + return stringifyToJsonValue(value); + } + + return undefined; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/serverSentEvents.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/serverSentEvents.gen.ts new file mode 100644 index 0000000000..6aa6cf02a4 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/serverSentEvents.gen.ts @@ -0,0 +1,243 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Config } from './types.gen'; + +export type ServerSentEventsOptions = Omit & + Pick & { + /** + * Fetch API implementation. You can use this option to provide a custom + * fetch instance. + * + * @default globalThis.fetch + */ + fetch?: typeof fetch; + /** + * Implementing clients can call request interceptors inside this hook. + */ + onRequest?: (url: string, init: RequestInit) => Promise; + /** + * Callback invoked when a network or parsing error occurs during streaming. + * + * This option applies only if the endpoint returns a stream of events. + * + * @param error The error that occurred. + */ + onSseError?: (error: unknown) => void; + /** + * Callback invoked when an event is streamed from the server. + * + * This option applies only if the endpoint returns a stream of events. + * + * @param event Event streamed from the server. + * @returns Nothing (void). + */ + onSseEvent?: (event: StreamEvent) => void; + serializedBody?: RequestInit['body']; + /** + * Default retry delay in milliseconds. + * + * This option applies only if the endpoint returns a stream of events. + * + * @default 3000 + */ + sseDefaultRetryDelay?: number; + /** + * Maximum number of retry attempts before giving up. + */ + sseMaxRetryAttempts?: number; + /** + * Maximum retry delay in milliseconds. + * + * Applies only when exponential backoff is used. + * + * This option applies only if the endpoint returns a stream of events. + * + * @default 30000 + */ + sseMaxRetryDelay?: number; + /** + * Optional sleep function for retry backoff. + * + * Defaults to using `setTimeout`. + */ + sseSleepFn?: (ms: number) => Promise; + url: string; + }; + +export interface StreamEvent { + data: TData; + event?: string; + id?: string; + retry?: number; +} + +export type ServerSentEventsResult = { + stream: AsyncGenerator< + TData extends Record ? TData[keyof TData] : TData, + TReturn, + TNext + >; +}; + +export const createSseClient = ({ + onRequest, + onSseError, + onSseEvent, + responseTransformer, + responseValidator, + sseDefaultRetryDelay, + sseMaxRetryAttempts, + sseMaxRetryDelay, + sseSleepFn, + url, + ...options +}: ServerSentEventsOptions): ServerSentEventsResult => { + let lastEventId: string | undefined; + + const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + + const createStream = async function* () { + let retryDelay: number = sseDefaultRetryDelay ?? 3000; + let attempt = 0; + const signal = options.signal ?? new AbortController().signal; + + while (true) { + if (signal.aborted) break; + + attempt++; + + const headers = + options.headers instanceof Headers + ? options.headers + : new Headers(options.headers as Record | undefined); + + if (lastEventId !== undefined) { + headers.set('Last-Event-ID', lastEventId); + } + + try { + const requestInit: RequestInit = { + redirect: 'follow', + ...options, + body: options.serializedBody, + headers, + signal, + }; + let request = new Request(url, requestInit); + if (onRequest) { + request = await onRequest(url, requestInit); + } + // fetch must be assigned here, otherwise it would throw the error: + // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation + const _fetch = options.fetch ?? globalThis.fetch; + const response = await _fetch(request); + + if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); + + if (!response.body) throw new Error('No body in SSE response'); + + const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); + + let buffer = ''; + + const abortHandler = () => { + try { + reader.cancel(); + } catch { + // noop + } + }; + + signal.addEventListener('abort', abortHandler); + + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + buffer += value; + // Normalize line endings: CRLF -> LF, then CR -> LF + buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); + + const chunks = buffer.split('\n\n'); + buffer = chunks.pop() ?? ''; + + for (const chunk of chunks) { + const lines = chunk.split('\n'); + const dataLines: Array = []; + let eventName: string | undefined; + + for (const line of lines) { + if (line.startsWith('data:')) { + dataLines.push(line.replace(/^data:\s*/, '')); + } else if (line.startsWith('event:')) { + eventName = line.replace(/^event:\s*/, ''); + } else if (line.startsWith('id:')) { + lastEventId = line.replace(/^id:\s*/, ''); + } else if (line.startsWith('retry:')) { + const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); + if (!Number.isNaN(parsed)) { + retryDelay = parsed; + } + } + } + + let data: unknown; + let parsedJson = false; + + if (dataLines.length) { + const rawData = dataLines.join('\n'); + try { + data = JSON.parse(rawData); + parsedJson = true; + } catch { + data = rawData; + } + } + + if (parsedJson) { + if (responseValidator) { + await responseValidator(data); + } + + if (responseTransformer) { + data = await responseTransformer(data); + } + } + + onSseEvent?.({ + data, + event: eventName, + id: lastEventId, + retry: retryDelay, + }); + + if (dataLines.length) { + yield data as any; + } + } + } + } finally { + signal.removeEventListener('abort', abortHandler); + reader.releaseLock(); + } + + break; // exit loop on normal completion + } catch (error) { + // connection failed or aborted; retry after delay + onSseError?.(error); + + if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { + break; // stop after firing error + } + + // exponential backoff: double retry each attempt, cap at 30s + const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); + await sleep(backoff); + } + } + }; + + const stream = createStream(); + + return { stream }; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/types.gen.ts new file mode 100644 index 0000000000..97463257e4 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/types.gen.ts @@ -0,0 +1,104 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Auth, AuthToken } from './auth.gen'; +import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; + +export type HttpMethod = + | 'connect' + | 'delete' + | 'get' + | 'head' + | 'options' + | 'patch' + | 'post' + | 'put' + | 'trace'; + +export type Client< + RequestFn = never, + Config = unknown, + MethodFn = never, + BuildUrlFn = never, + SseFn = never, +> = { + /** + * Returns the final request URL. + */ + buildUrl: BuildUrlFn; + getConfig: () => Config; + request: RequestFn; + setConfig: (config: Config) => Config; +} & { + [K in HttpMethod]: MethodFn; +} & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); + +export interface Config { + /** + * Auth token or a function returning auth token. The resolved value will be + * added to the request payload as defined by its `security` array. + */ + auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; + /** + * A function for serializing request body parameter. By default, + * {@link JSON.stringify()} will be used. + */ + bodySerializer?: BodySerializer | null; + /** + * An object containing any HTTP headers that you want to pre-populate your + * `Headers` object with. + * + * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} + */ + headers?: + | RequestInit['headers'] + | Record< + string, + string | number | boolean | (string | number | boolean)[] | null | undefined | unknown + >; + /** + * The request method. + * + * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} + */ + method?: Uppercase; + /** + * A function for serializing request query parameters. By default, arrays + * will be exploded in form style, objects will be exploded in deepObject + * style, and reserved characters are percent-encoded. + * + * This method will have no effect if the native `paramsSerializer()` Axios + * API function is used. + * + * {@link https://swagger.io/docs/specification/serialization/#query View examples} + */ + querySerializer?: QuerySerializer | QuerySerializerOptions; + /** + * A function validating request data. This is useful if you want to ensure + * the request conforms to the desired shape, so it can be safely sent to + * the server. + */ + requestValidator?: (data: unknown) => Promise; + /** + * A function transforming response data before it's returned. This is useful + * for post-processing data, e.g. converting ISO strings into Date objects. + */ + responseTransformer?: (data: unknown) => Promise; + /** + * A function validating response data. This is useful if you want to ensure + * the response conforms to the desired shape, so it can be safely passed to + * the transformers and returned to the user. + */ + responseValidator?: (data: unknown) => Promise; +} + +type IsExactlyNeverOrNeverUndefined = [T] extends [never] + ? true + : [T] extends [never | undefined] + ? [undefined] extends [T] + ? false + : true + : false; + +export type OmitNever> = { + [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/utils.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/utils.gen.ts new file mode 100644 index 0000000000..e7ddbe3541 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/core/utils.gen.ts @@ -0,0 +1,140 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; +import { + type ArraySeparatorStyle, + serializeArrayParam, + serializeObjectParam, + serializePrimitiveParam, +} from './pathSerializer.gen'; + +export interface PathSerializer { + path: Record; + url: string; +} + +export const PATH_PARAM_RE = /\{[^{}]+\}/g; + +export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { + let url = _url; + const matches = _url.match(PATH_PARAM_RE); + if (matches) { + for (const match of matches) { + let explode = false; + let name = match.substring(1, match.length - 1); + let style: ArraySeparatorStyle = 'simple'; + + if (name.endsWith('*')) { + explode = true; + name = name.substring(0, name.length - 1); + } + + if (name.startsWith('.')) { + name = name.substring(1); + style = 'label'; + } else if (name.startsWith(';')) { + name = name.substring(1); + style = 'matrix'; + } + + const value = path[name]; + + if (value === undefined || value === null) { + continue; + } + + if (Array.isArray(value)) { + url = url.replace(match, serializeArrayParam({ explode, name, style, value })); + continue; + } + + if (typeof value === 'object') { + url = url.replace( + match, + serializeObjectParam({ + explode, + name, + style, + value: value as Record, + valueOnly: true, + }), + ); + continue; + } + + if (style === 'matrix') { + url = url.replace( + match, + `;${serializePrimitiveParam({ + name, + value: value as string, + })}`, + ); + continue; + } + + const replaceValue = encodeURIComponent( + style === 'label' ? `.${value as string}` : (value as string), + ); + url = url.replace(match, replaceValue); + } + } + return url; +}; + +export const getUrl = ({ + baseUrl, + path, + query, + querySerializer, + url: _url, +}: { + baseUrl?: string; + path?: Record; + query?: Record; + querySerializer: QuerySerializer; + url: string; +}) => { + const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; + let url = (baseUrl ?? '') + pathUrl; + if (path) { + url = defaultPathSerializer({ path, url }); + } + let search = query ? querySerializer(query) : ''; + if (search.startsWith('?')) { + search = search.substring(1); + } + if (search) { + url += `?${search}`; + } + return url; +}; + +export function getValidRequestBody(options: { + body?: unknown; + bodySerializer?: BodySerializer | null; + serializedBody?: unknown; +}) { + const hasBody = options.body !== undefined; + const isSerializedBody = hasBody && options.bodySerializer; + + if (isSerializedBody) { + if ('serializedBody' in options) { + const hasSerializedBody = + options.serializedBody !== undefined && options.serializedBody !== ''; + + return hasSerializedBody ? options.serializedBody : null; + } + + // not all clients implement a serializedBody property (i.e. client-axios) + return options.body !== '' ? options.body : null; + } + + // plain/text body + if (hasBody) { + return options.body; + } + + // no body was provided + return undefined; +} diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/index.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/index.ts new file mode 100644 index 0000000000..6e132194fd --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/index.ts @@ -0,0 +1,4 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; +export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/sdk.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/sdk.gen.ts new file mode 100644 index 0000000000..e48dcff8cf --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/sdk.gen.ts @@ -0,0 +1,206 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; +import { client } from './client.gen'; +import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; + +export type Options = Options2 & { + /** + * You can provide a client instance returned by `createClient()` instead of + * individual options. This might be also useful if you want to implement a + * custom client. + */ + client?: Client; + /** + * You can pass arbitrary values through the `meta` object. This can be + * used to access values that aren't defined as part of the SDK function. + */ + meta?: Record; +}; + +export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); + +export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); + +export const import_ = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/no+tag', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); + +export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); + +export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); + +export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); + +export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); + +export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); + +export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); + +export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); + +export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); + +export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); + +export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); + +export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); + +/** + * @deprecated + */ +export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); + +export const callWithParameters = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/parameters/{parameterPath}', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ + url: '/api/v{api-version}/parameters', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/parameters', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ + url: '/api/v{api-version}/requestBody', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options?.headers + } +}); + +export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ + ...formDataBodySerializer, + url: '/api/v{api-version}/formData', + ...options, + headers: { + 'Content-Type': null, + ...options?.headers + } +}); + +export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); + +export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); + +export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); + +export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); + +export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); + +export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); + +export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); + +export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); + +export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); + +export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); + +export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); + +export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); + +export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); + +export const uploadFile = (options: Options) => (options.client ?? client).post({ + ...urlSearchParamsBodySerializer, + url: '/api/v{api-version}/upload', + ...options, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + ...options.headers + } +}); + +export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); + +export const complexTypes = (options: Options) => (options.client ?? client).get({ + querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, + url: '/api/v{api-version}/complex', + ...options +}); + +export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); + +export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ + ...formDataBodySerializer, + url: '/api/v{api-version}/multipart', + ...options, + headers: { + 'Content-Type': null, + ...options?.headers + } +}); + +export const complexParams = (options: Options) => (options.client ?? client).put({ + url: '/api/v{api-version}/complex/{id}', + ...options, + headers: { + 'Content-Type': 'application/json-patch+json', + ...options.headers + } +}); + +export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); + +export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); + +export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); + +/** + * Login User + */ +export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ + ...urlSearchParamsBodySerializer, + url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', + ...options, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + ...options.headers + } +}); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/types.gen.ts new file mode 100644 index 0000000000..3287ee8737 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/skipToken/types.gen.ts @@ -0,0 +1,2081 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type ClientOptions = { + baseUrl: 'http://localhost:3000/base' | (string & {}); +}; + +/** + * Model with number-only name + */ +export type _400 = string; + +export type ExternalRefA = ExternalSharedModel; + +export type ExternalRefB = ExternalSharedModel; + +/** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ +export type CamelCaseCommentWithBreaks = number; + +/** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ +export type CommentWithBreaks = number; + +/** + * Testing backticks in string: `backticks` and ```multiple backticks``` should work + */ +export type CommentWithBackticks = number; + +/** + * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work + */ +export type CommentWithBackticksAndQuotes = number; + +/** + * Testing slashes in string: \backwards\\\ and /forwards/// should work + */ +export type CommentWithSlashes = number; + +/** + * Testing expression placeholders in string: ${expression} should work + */ +export type CommentWithExpressionPlaceholders = number; + +/** + * Testing quotes in string: 'single quote''' and "double quotes""" should work + */ +export type CommentWithQuotes = number; + +/** + * Testing reserved characters in string: * inline * and ** inline ** should work + */ +export type CommentWithReservedCharacters = number; + +/** + * This is a simple number + */ +export type SimpleInteger = number; + +/** + * This is a simple boolean + */ +export type SimpleBoolean = boolean; + +/** + * This is a simple string + */ +export type SimpleString = string; + +/** + * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) + */ +export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; + +/** + * This is a simple file + */ +export type SimpleFile = Blob | File; + +/** + * This is a simple reference + */ +export type SimpleReference = ModelWithString; + +/** + * This is a simple string + */ +export type SimpleStringWithPattern = string | null; + +/** + * This is a simple enum with strings + */ +export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; + +export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; + +/** + * This is a simple enum with numbers + */ +export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; + +/** + * Success=1,Warning=2,Error=3 + */ +export type EnumFromDescription = number; + +/** + * This is a simple enum with numbers + */ +export type EnumWithExtensions = 200 | 400 | 500; + +export type EnumWithXEnumNames = 0 | 1 | 2; + +/** + * This is a simple array with numbers + */ +export type ArrayWithNumbers = Array; + +/** + * This is a simple array with booleans + */ +export type ArrayWithBooleans = Array; + +/** + * This is a simple array with strings + */ +export type ArrayWithStrings = Array; + +/** + * This is a simple array with references + */ +export type ArrayWithReferences = Array; + +/** + * This is a simple array containing an array + */ +export type ArrayWithArray = Array>; + +/** + * This is a simple array with properties + */ +export type ArrayWithProperties = Array<{ + '16x16'?: CamelCaseCommentWithBreaks; + bar?: string; +}>; + +/** + * This is a simple array with any of properties + */ +export type ArrayWithAnyOfProperties = Array<{ + foo?: string; +} | { + bar?: string; +}>; + +export type AnyOfAnyAndNull = { + data?: unknown; +}; + +/** + * This is a simple array with any of properties + */ +export type AnyOfArrays = { + results?: Array<{ + foo?: string; + } | { + bar?: string; + }>; +}; + +/** + * This is a string dictionary + */ +export type DictionaryWithString = { + [key: string]: string; +}; + +export type DictionaryWithPropertiesAndAdditionalProperties = { + foo?: number; + bar?: boolean; + [key: string]: string | number | boolean | undefined; +}; + +/** + * This is a string reference + */ +export type DictionaryWithReference = { + [key: string]: ModelWithString; +}; + +/** + * This is a complex dictionary + */ +export type DictionaryWithArray = { + [key: string]: Array; +}; + +/** + * This is a string dictionary + */ +export type DictionaryWithDictionary = { + [key: string]: { + [key: string]: string; + }; +}; + +/** + * This is a complex dictionary + */ +export type DictionaryWithProperties = { + [key: string]: { + foo?: string; + bar?: string; + }; +}; + +/** + * This is a model with one number property + */ +export type ModelWithInteger = { + /** + * This is a simple number property + */ + prop?: number; +}; + +/** + * This is a model with one boolean property + */ +export type ModelWithBoolean = { + /** + * This is a simple boolean property + */ + prop?: boolean; +}; + +/** + * This is a model with one string property + */ +export type ModelWithString = { + /** + * This is a simple string property + */ + prop?: string; +}; + +/** + * This is a model with one string property + */ +export type ModelWithStringError = { + /** + * This is a simple string property + */ + prop?: string; +}; + +/** + * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) + */ +export type ModelFromZendesk = string; + +/** + * This is a model with one string property + */ +export type ModelWithNullableString = { + /** + * This is a simple string property + */ + nullableProp1?: string | null; + /** + * This is a simple string property + */ + nullableRequiredProp1: string | null; + /** + * This is a simple string property + */ + nullableProp2?: string | null; + /** + * This is a simple string property + */ + nullableRequiredProp2: string | null; + /** + * This is a simple enum with strings + */ + 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; +}; + +/** + * This is a model with one enum + */ +export type ModelWithEnum = { + /** + * This is a simple enum with strings + */ + 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; + /** + * These are the HTTP error code enums + */ + statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; + /** + * Simple boolean enum + */ + bool?: true; +}; + +/** + * This is a model with one enum with escaped name + */ +export type ModelWithEnumWithHyphen = { + /** + * Foo-Bar-Baz-Qux + */ + 'foo-bar-baz-qux'?: '3.0'; +}; + +/** + * This is a model with one enum + */ +export type ModelWithEnumFromDescription = { + /** + * Success=1,Warning=2,Error=3 + */ + test?: number; +}; + +/** + * This is a model with nested enums + */ +export type ModelWithNestedEnums = { + dictionaryWithEnum?: { + [key: string]: 'Success' | 'Warning' | 'Error'; + }; + dictionaryWithEnumFromDescription?: { + [key: string]: number; + }; + arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; + arrayWithDescription?: Array; + /** + * This is a simple enum with strings + */ + 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; +}; + +/** + * This is a model with one property containing a reference + */ +export type ModelWithReference = { + prop?: ModelWithProperties; +}; + +/** + * This is a model with one property containing an array + */ +export type ModelWithArrayReadOnlyAndWriteOnly = { + prop?: Array; + propWithFile?: Array; + propWithNumber?: Array; +}; + +/** + * This is a model with one property containing an array + */ +export type ModelWithArray = { + prop?: Array; + propWithFile?: Array; + propWithNumber?: Array; +}; + +/** + * This is a model with one property containing a dictionary + */ +export type ModelWithDictionary = { + prop?: { + [key: string]: string; + }; +}; + +/** + * This is a deprecated model with a deprecated property + * + * @deprecated + */ +export type DeprecatedModel = { + /** + * This is a deprecated property + * + * @deprecated + */ + prop?: string; +}; + +/** + * This is a model with one property containing a circular reference + */ +export type ModelWithCircularReference = { + prop?: ModelWithCircularReference; +}; + +/** + * This is a model with one property with a 'one of' relationship + */ +export type CompositionWithOneOf = { + propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; +}; + +/** + * This is a model with one property with a 'one of' relationship where the options are not $ref + */ +export type CompositionWithOneOfAnonymous = { + propA?: { + propA?: string; + } | string | number; +}; + +/** + * Circle + */ +export type ModelCircle = { + kind: string; + radius?: number; +}; + +/** + * Square + */ +export type ModelSquare = { + kind: string; + sideLength?: number; +}; + +/** + * This is a model with one property with a 'one of' relationship where the options are not $ref + */ +export type CompositionWithOneOfDiscriminator = ({ + kind: 'circle'; +} & ModelCircle) | ({ + kind: 'square'; +} & ModelSquare); + +/** + * This is a model with one property with a 'any of' relationship + */ +export type CompositionWithAnyOf = { + propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; +}; + +/** + * This is a model with one property with a 'any of' relationship where the options are not $ref + */ +export type CompositionWithAnyOfAnonymous = { + propA?: { + propA?: string; + } | string | number; +}; + +/** + * This is a model with nested 'any of' property with a type null + */ +export type CompositionWithNestedAnyAndTypeNull = { + propA?: Array | Array; +}; + +export type _3eNum1Период = 'Bird' | 'Dog'; + +export type ConstValue = 'ConstValue'; + +/** + * This is a model with one property with a 'any of' relationship where the options are not $ref + */ +export type CompositionWithNestedAnyOfAndNull = { + propA?: Array<_3eNum1Период | ConstValue> | null; +}; + +/** + * This is a model with one property with a 'one of' relationship + */ +export type CompositionWithOneOfAndNullable = { + propA?: { + boolean?: boolean; + } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; +}; + +/** + * This is a model that contains a simple dictionary within composition + */ +export type CompositionWithOneOfAndSimpleDictionary = { + propA?: boolean | { + [key: string]: number; + }; +}; + +/** + * This is a model that contains a dictionary of simple arrays within composition + */ +export type CompositionWithOneOfAndSimpleArrayDictionary = { + propA?: boolean | { + [key: string]: Array; + }; +}; + +/** + * This is a model that contains a dictionary of complex arrays (composited) within composition + */ +export type CompositionWithOneOfAndComplexArrayDictionary = { + propA?: boolean | { + [key: string]: Array; + }; +}; + +/** + * This is a model with one property with a 'all of' relationship + */ +export type CompositionWithAllOfAndNullable = { + propA?: ({ + boolean?: boolean; + } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; +}; + +/** + * This is a model with one property with a 'any of' relationship + */ +export type CompositionWithAnyOfAndNullable = { + propA?: { + boolean?: boolean; + } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; +}; + +/** + * This is a base model with two simple optional properties + */ +export type CompositionBaseModel = { + firstName?: string; + lastname?: string; +}; + +/** + * This is a model that extends the base model + */ +export type CompositionExtendedModel = CompositionBaseModel & { + age: number; + firstName: string; + lastname: string; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithProperties = { + required: string; + readonly requiredAndReadOnly: string; + requiredAndNullable: string | null; + string?: string; + number?: number; + boolean?: boolean; + reference?: ModelWithString; + 'property with space'?: string; + default?: string; + try?: string; + readonly '@namespace.string'?: string; + readonly '@namespace.integer'?: number; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithNestedProperties = { + readonly first: { + readonly second: { + readonly third: string | null; + } | null; + } | null; +}; + +/** + * This is a model with duplicated properties + */ +export type ModelWithDuplicateProperties = { + prop?: ModelWithString; +}; + +/** + * This is a model with ordered properties + */ +export type ModelWithOrderedProperties = { + zebra?: string; + apple?: string; + hawaii?: string; +}; + +/** + * This is a model with duplicated imports + */ +export type ModelWithDuplicateImports = { + propA?: ModelWithString; + propB?: ModelWithString; + propC?: ModelWithString; +}; + +/** + * This is a model that extends another model + */ +export type ModelThatExtends = ModelWithString & { + propExtendsA?: string; + propExtendsB?: ModelWithString; +}; + +/** + * This is a model that extends another model + */ +export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { + propExtendsC?: string; + propExtendsD?: ModelWithString; +}; + +/** + * This is a model that contains a some patterns + */ +export type ModelWithPattern = { + key: string; + name: string; + readonly enabled?: boolean; + readonly modified?: string; + id?: string; + text?: string; + patternWithSingleQuotes?: string; + patternWithNewline?: string; + patternWithBacktick?: string; + patternWithUnicode?: string; +}; + +export type File = { + /** + * Id + */ + readonly id?: string; + /** + * Updated at + */ + readonly updated_at?: string; + /** + * Created at + */ + readonly created_at?: string; + /** + * Mime + */ + mime: string; + /** + * File + */ + readonly file?: string; +}; + +export type Default = { + name?: string; +}; + +export type Pageable = { + page?: number; + size?: number; + sort?: Array; +}; + +/** + * This is a free-form object without additionalProperties. + */ +export type FreeFormObjectWithoutAdditionalProperties = { + [key: string]: unknown; +}; + +/** + * This is a free-form object with additionalProperties: true. + */ +export type FreeFormObjectWithAdditionalPropertiesEqTrue = { + [key: string]: unknown; +}; + +/** + * This is a free-form object with additionalProperties: {}. + */ +export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { + [key: string]: unknown; +}; + +export type ModelWithConst = { + String?: 'String'; + number?: 0; + null?: unknown; + withType?: 'Some string'; +}; + +/** + * This is a model with one property and additionalProperties: true + */ +export type ModelWithAdditionalPropertiesEqTrue = { + /** + * This is a simple string property + */ + prop?: string; + [key: string]: unknown; +}; + +export type NestedAnyOfArraysNullable = { + nullableArray?: Array | null; +}; + +export type CompositionWithOneOfAndProperties = ({ + foo: SimpleParameter; +} | { + bar: NonAsciiStringæøåÆøÅöôêÊ字符串; +}) & { + baz: number | null; + qux: number; +}; + +/** + * An object that can be null + */ +export type NullableObject = { + foo?: string; +} | null; + +/** + * Some % character + */ +export type CharactersInDescription = string; + +export type ModelWithNullableObject = { + data?: NullableObject; +}; + +/** + * An object with additional properties that can be null + */ +export type ModelWithAdditionalPropertiesRef = { + [key: string]: NullableObject | null; +}; + +export type ModelWithOneOfEnum = { + foo: 'Bar'; +} | { + foo: 'Baz'; +} | { + foo: 'Qux'; +} | { + content: string; + foo: 'Quux'; +} | { + content: [ + string, + string + ]; + foo: 'Corge'; +}; + +export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; + +export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; + +export type ModelWithNestedArrayEnumsData = { + foo?: Array; + bar?: Array; +}; + +export type ModelWithNestedArrayEnums = { + array_strings?: Array; + data?: ModelWithNestedArrayEnumsData; +}; + +export type ModelWithNestedCompositionEnums = { + foo?: ModelWithNestedArrayEnumsDataFoo; +}; + +export type ModelWithReadOnlyAndWriteOnly = { + foo: string; + readonly bar: string; +}; + +export type ModelWithConstantSizeArray = [ + number, + number +]; + +export type ModelWithAnyOfConstantSizeArray = [ + number | string, + number | string, + number | string +]; + +export type ModelWithPrefixItemsConstantSizeArray = Array; + +export type ModelWithAnyOfConstantSizeArrayNullable = [ + number | null | string, + number | null | string, + number | null | string +]; + +export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ + number | Import, + number | Import +]; + +export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ + number & string, + number & string +]; + +export type ModelWithNumericEnumUnion = { + /** + * Период + */ + value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; +}; + +/** + * Some description with `back ticks` + */ +export type ModelWithBackticksInDescription = { + /** + * The template `that` should be used for parsing and importing the contents of the CSV file. + * + *

There is one placeholder currently supported:

  • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

Example of a correct JSON template:

+ *
+     * [
+     * {
+     * "resourceType": "Asset",
+     * "identifier": {
+     * "name": "${1}",
+     * "domain": {
+     * "name": "${2}",
+     * "community": {
+     * "name": "Some Community"
+     * }
+     * }
+     * },
+     * "attributes" : {
+     * "00000000-0000-0000-0000-000000003115" : [ {
+     * "value" : "${3}"
+     * } ],
+     * "00000000-0000-0000-0000-000000000222" : [ {
+     * "value" : "${4}"
+     * } ]
+     * }
+     * }
+     * ]
+     * 
+ */ + template?: string; +}; + +export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { + baz: number | null; + qux: number; +}; + +/** + * Model used to test deduplication strategy (unused) + */ +export type ParameterSimpleParameterUnused = string; + +/** + * Model used to test deduplication strategy + */ +export type PostServiceWithEmptyTagResponse = string; + +/** + * Model used to test deduplication strategy + */ +export type PostServiceWithEmptyTagResponse2 = string; + +/** + * Model used to test deduplication strategy + */ +export type DeleteFooData = string; + +/** + * Model used to test deduplication strategy + */ +export type DeleteFooData2 = string; + +/** + * Model with restricted keyword name + */ +export type Import = string; + +export type SchemaWithFormRestrictedKeys = { + description?: string; + 'x-enum-descriptions'?: string; + 'x-enum-varnames'?: string; + 'x-enumNames'?: string; + title?: string; + object?: { + description?: string; + 'x-enum-descriptions'?: string; + 'x-enum-varnames'?: string; + 'x-enumNames'?: string; + title?: string; + }; + array?: Array<{ + description?: string; + 'x-enum-descriptions'?: string; + 'x-enum-varnames'?: string; + 'x-enumNames'?: string; + title?: string; + }>; +}; + +/** + * This schema was giving PascalCase transformations a hard time + */ +export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { + /** + * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. + */ + preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; +}; + +/** + * This schema was giving PascalCase transformations a hard time + */ +export type IoK8sApimachineryPkgApisMetaV1Preconditions = { + /** + * Specifies the target ResourceVersion + */ + resourceVersion?: string; + /** + * Specifies the target UID. + */ + uid?: string; +}; + +export type AdditionalPropertiesUnknownIssue = { + [key: string]: string | number; +}; + +export type AdditionalPropertiesUnknownIssue2 = { + [key: string]: string | number; +}; + +export type AdditionalPropertiesUnknownIssue3 = string & { + entries: { + [key: string]: AdditionalPropertiesUnknownIssue; + }; +}; + +export type AdditionalPropertiesIntegerIssue = { + value: number; + [key: string]: number; +}; + +export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; + +export type GenericSchemaDuplicateIssue1SystemBoolean = { + item?: boolean; + error?: string | null; + readonly hasError?: boolean; + data?: { + [key: string]: never; + }; +}; + +export type GenericSchemaDuplicateIssue1SystemString = { + item?: string | null; + error?: string | null; + readonly hasError?: boolean; +}; + +export type ExternalSharedModel = { + id: string; + name?: string; +}; + +/** + * This is a model with one property containing a reference + */ +export type ModelWithReferenceWritable = { + prop?: ModelWithPropertiesWritable; +}; + +/** + * This is a model with one property containing an array + */ +export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { + prop?: Array; + propWithFile?: Array; + propWithNumber?: Array; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithPropertiesWritable = { + required: string; + requiredAndNullable: string | null; + string?: string; + number?: number; + boolean?: boolean; + reference?: ModelWithString; + 'property with space'?: string; + default?: string; + try?: string; +}; + +/** + * This is a model that contains a some patterns + */ +export type ModelWithPatternWritable = { + key: string; + name: string; + id?: string; + text?: string; + patternWithSingleQuotes?: string; + patternWithNewline?: string; + patternWithBacktick?: string; + patternWithUnicode?: string; +}; + +export type FileWritable = { + /** + * Mime + */ + mime: string; +}; + +export type ModelWithReadOnlyAndWriteOnlyWritable = { + foo: string; + baz: string; +}; + +export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ + number | Import, + number | Import +]; + +export type AdditionalPropertiesUnknownIssueWritable = { + [key: string]: string | number; +}; + +export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; + +export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { + item?: boolean; + error?: string | null; + data?: { + [key: string]: never; + }; +}; + +export type GenericSchemaDuplicateIssue1SystemStringWritable = { + item?: string | null; + error?: string | null; +}; + +/** + * This is a reusable parameter + */ +export type SimpleParameter = string; + +/** + * Parameter with illegal characters + */ +export type XFooBar = ModelWithString; + +export type SimpleRequestBody = ModelWithString; + +export type SimpleFormData = ModelWithString; + +export type ExportData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type PatchApiVbyApiVersionNoTagData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type PatchApiVbyApiVersionNoTagResponses = { + /** + * OK + */ + default: unknown; +}; + +export type ImportData = { + body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type ImportResponses = { + /** + * Success + */ + 200: ModelFromZendesk; + /** + * Default success response + */ + default: ModelWithReadOnlyAndWriteOnly; +}; + +export type ImportResponse = ImportResponses[keyof ImportResponses]; + +export type FooWowData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type FooWowResponses = { + /** + * OK + */ + default: unknown; +}; + +export type ApiVVersionODataControllerCountData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple/$count'; +}; + +export type ApiVVersionODataControllerCountResponses = { + /** + * Success + */ + 200: ModelFromZendesk; +}; + +export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; + +export type GetApiVbyApiVersionSimpleOperationData = { + body?: never; + path: { + /** + * foo in method + */ + foo_param: string; + }; + query?: never; + url: '/api/v{api-version}/simple:operation'; +}; + +export type GetApiVbyApiVersionSimpleOperationErrors = { + /** + * Default error response + */ + default: ModelWithBoolean; +}; + +export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; + +export type GetApiVbyApiVersionSimpleOperationResponses = { + /** + * Response is a simple number + */ + 200: number; +}; + +export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; + +export type DeleteCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type GetCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type HeadCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type OptionsCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PatchCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PostCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PutCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type DeleteFooData3 = { + body?: never; + headers: { + /** + * Parameter with illegal characters + */ + 'x-Foo-Bar': ModelWithString; + }; + path: { + /** + * foo in method + */ + foo_param: string; + /** + * bar in method + */ + BarParam: string; + }; + query?: never; + url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; +}; + +export type CallWithDescriptionsData = { + body?: never; + path?: never; + query?: { + /** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ + parameterWithBreaks?: string; + /** + * Testing backticks in string: `backticks` and ```multiple backticks``` should work + */ + parameterWithBackticks?: string; + /** + * Testing slashes in string: \backwards\\\ and /forwards/// should work + */ + parameterWithSlashes?: string; + /** + * Testing expression placeholders in string: ${expression} should work + */ + parameterWithExpressionPlaceholders?: string; + /** + * Testing quotes in string: 'single quote''' and "double quotes""" should work + */ + parameterWithQuotes?: string; + /** + * Testing reserved characters in string: * inline * and ** inline ** should work + */ + parameterWithReservedCharacters?: string; + }; + url: '/api/v{api-version}/descriptions'; +}; + +export type DeprecatedCallData = { + body?: never; + headers: { + /** + * This parameter is deprecated + * + * @deprecated + */ + parameter: DeprecatedModel | null; + }; + path?: never; + query?: never; + url: '/api/v{api-version}/parameters/deprecated'; +}; + +export type CallWithParametersData = { + /** + * This is the parameter that goes into the body + */ + body: { + [key: string]: unknown; + } | null; + headers: { + /** + * This is the parameter that goes into the header + */ + parameterHeader: string | null; + }; + path: { + /** + * This is the parameter that goes into the path + */ + parameterPath: string | null; + /** + * api-version should be required in standalone clients + */ + 'api-version': string | null; + }; + query: { + foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; + foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; + /** + * This is the parameter that goes into the query params + */ + cursor: string | null; + }; + url: '/api/v{api-version}/parameters/{parameterPath}'; +}; + +export type CallWithWeirdParameterNamesData = { + /** + * This is the parameter that goes into the body + */ + body: ModelWithString | null; + headers: { + /** + * This is the parameter that goes into the request header + */ + 'parameter.header': string | null; + }; + path: { + /** + * This is the parameter that goes into the path + */ + 'parameter.path.1'?: string; + /** + * This is the parameter that goes into the path + */ + 'parameter-path-2'?: string; + /** + * This is the parameter that goes into the path + */ + 'PARAMETER-PATH-3'?: string; + /** + * api-version should be required in standalone clients + */ + 'api-version': string | null; + }; + query: { + /** + * This is the parameter with a reserved keyword + */ + default?: string; + /** + * This is the parameter that goes into the request query params + */ + 'parameter-query': string | null; + }; + url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; +}; + +export type GetCallWithOptionalParamData = { + /** + * This is a required parameter + */ + body: ModelWithOneOfEnum; + path?: never; + query?: { + /** + * This is an optional parameter + */ + page?: number; + }; + url: '/api/v{api-version}/parameters'; +}; + +export type PostCallWithOptionalParamData = { + /** + * This is an optional parameter + */ + body?: { + offset?: number | null; + }; + path?: never; + query: { + /** + * This is a required parameter + */ + parameter: Pageable; + }; + url: '/api/v{api-version}/parameters'; +}; + +export type PostCallWithOptionalParamResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Success + */ + 204: void; +}; + +export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; + +export type PostApiVbyApiVersionRequestBodyData = { + /** + * A reusable request body + */ + body?: SimpleRequestBody; + path?: never; + query?: { + /** + * This is a reusable parameter + */ + parameter?: string; + }; + url: '/api/v{api-version}/requestBody'; +}; + +export type PostApiVbyApiVersionFormDataData = { + /** + * A reusable request body + */ + body?: SimpleFormData; + path?: never; + query?: { + /** + * This is a reusable parameter + */ + parameter?: string; + }; + url: '/api/v{api-version}/formData'; +}; + +export type CallWithDefaultParametersData = { + body?: never; + path?: never; + query?: { + /** + * This is a simple string with default value + */ + parameterString?: string | null; + /** + * This is a simple number with default value + */ + parameterNumber?: number | null; + /** + * This is a simple boolean with default value + */ + parameterBoolean?: boolean | null; + /** + * This is a simple enum with default value + */ + parameterEnum?: 'Success' | 'Warning' | 'Error'; + /** + * This is a simple model with default value + */ + parameterModel?: ModelWithString | null; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type CallWithDefaultOptionalParametersData = { + body?: never; + path?: never; + query?: { + /** + * This is a simple string that is optional with default value + */ + parameterString?: string; + /** + * This is a simple number that is optional with default value + */ + parameterNumber?: number; + /** + * This is a simple boolean that is optional with default value + */ + parameterBoolean?: boolean; + /** + * This is a simple enum that is optional with default value + */ + parameterEnum?: 'Success' | 'Warning' | 'Error'; + /** + * This is a simple model that is optional with default value + */ + parameterModel?: ModelWithString; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type CallToTestOrderOfParamsData = { + body?: never; + path?: never; + query: { + /** + * This is a optional string with default + */ + parameterOptionalStringWithDefault?: string; + /** + * This is a optional string with empty default + */ + parameterOptionalStringWithEmptyDefault?: string; + /** + * This is a optional string with no default + */ + parameterOptionalStringWithNoDefault?: string; + /** + * This is a string with default + */ + parameterStringWithDefault: string; + /** + * This is a string with empty default + */ + parameterStringWithEmptyDefault: string; + /** + * This is a string with no default + */ + parameterStringWithNoDefault: string; + /** + * This is a string that can be null with no default + */ + parameterStringNullableWithNoDefault?: string | null; + /** + * This is a string that can be null with default + */ + parameterStringNullableWithDefault?: string | null; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type DuplicateNameData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName2Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName3Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName4Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type CallWithNoContentResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no-content'; +}; + +export type CallWithNoContentResponseResponses = { + /** + * Success + */ + 204: void; +}; + +export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; + +export type CallWithResponseAndNoContentResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/response-and-no-content'; +}; + +export type CallWithResponseAndNoContentResponseResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Success + */ + 204: void; +}; + +export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; + +export type DummyAData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/a'; +}; + +export type DummyAResponses = { + 200: _400; +}; + +export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; + +export type DummyBData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/b'; +}; + +export type DummyBResponses = { + /** + * Success + */ + 204: void; +}; + +export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; + +export type CallWithResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithResponseResponses = { + default: Import; +}; + +export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; + +export type CallWithDuplicateResponsesData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithDuplicateResponsesErrors = { + /** + * Message for 500 error + */ + 500: ModelWithStringError; + /** + * Message for 501 error + */ + 501: ModelWithStringError; + /** + * Message for 502 error + */ + 502: ModelWithStringError; + /** + * Message for 4XX errors + */ + '4XX': DictionaryWithArray; + /** + * Default error response + */ + default: ModelWithBoolean; +}; + +export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; + +export type CallWithDuplicateResponsesResponses = { + /** + * Message for 200 response + */ + 200: ModelWithBoolean & ModelWithInteger; + /** + * Message for 201 response + */ + 201: ModelWithString; + /** + * Message for 202 response + */ + 202: ModelWithString; +}; + +export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; + +export type CallWithResponsesData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithResponsesErrors = { + /** + * Message for 500 error + */ + 500: ModelWithStringError; + /** + * Message for 501 error + */ + 501: ModelWithStringError; + /** + * Message for 502 error + */ + 502: ModelWithStringError; + /** + * Message for default response + */ + default: ModelWithStringError; +}; + +export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; + +export type CallWithResponsesResponses = { + /** + * Message for 200 response + */ + 200: { + readonly '@namespace.string'?: string; + readonly '@namespace.integer'?: number; + readonly value?: Array; + }; + /** + * Message for 201 response + */ + 201: ModelThatExtends; + /** + * Message for 202 response + */ + 202: ModelThatExtendsExtends; +}; + +export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; + +export type CollectionFormatData = { + body?: never; + path?: never; + query: { + /** + * This is an array parameter that is sent as csv format (comma-separated values) + */ + parameterArrayCSV: Array | null; + /** + * This is an array parameter that is sent as ssv format (space-separated values) + */ + parameterArraySSV: Array | null; + /** + * This is an array parameter that is sent as tsv format (tab-separated values) + */ + parameterArrayTSV: Array | null; + /** + * This is an array parameter that is sent as pipes format (pipe-separated values) + */ + parameterArrayPipes: Array | null; + /** + * This is an array parameter that is sent as multi format (multiple parameter instances) + */ + parameterArrayMulti: Array | null; + }; + url: '/api/v{api-version}/collectionFormat'; +}; + +export type TypesData = { + body?: never; + path?: { + /** + * This is a number parameter + */ + id?: number; + }; + query: { + /** + * This is a number parameter + */ + parameterNumber: number; + /** + * This is a string parameter + */ + parameterString: string | null; + /** + * This is a boolean parameter + */ + parameterBoolean: boolean | null; + /** + * This is an object parameter + */ + parameterObject: { + [key: string]: unknown; + } | null; + /** + * This is an array parameter + */ + parameterArray: Array | null; + /** + * This is a dictionary parameter + */ + parameterDictionary: { + [key: string]: unknown; + } | null; + /** + * This is an enum parameter + */ + parameterEnum: 'Success' | 'Warning' | 'Error'; + }; + url: '/api/v{api-version}/types'; +}; + +export type TypesResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Response is a simple string + */ + 201: string; + /** + * Response is a simple boolean + */ + 202: boolean; + /** + * Response is a simple object + */ + 203: { + [key: string]: unknown; + }; +}; + +export type TypesResponse = TypesResponses[keyof TypesResponses]; + +export type UploadFileData = { + body: Blob | File; + path: { + /** + * api-version should be required in standalone clients + */ + 'api-version': string | null; + }; + query?: never; + url: '/api/v{api-version}/upload'; +}; + +export type UploadFileResponses = { + 200: boolean; +}; + +export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; + +export type FileResponseData = { + body?: never; + path: { + id: string; + /** + * api-version should be required in standalone clients + */ + 'api-version': string; + }; + query?: never; + url: '/api/v{api-version}/file/{id}'; +}; + +export type FileResponseResponses = { + /** + * Success + */ + 200: Blob | File; +}; + +export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; + +export type ComplexTypesData = { + body?: never; + path?: never; + query: { + /** + * Parameter containing object + */ + parameterObject: { + first?: { + second?: { + third?: string; + }; + }; + }; + /** + * Parameter containing reference + */ + parameterReference: ModelWithString; + }; + url: '/api/v{api-version}/complex'; +}; + +export type ComplexTypesErrors = { + /** + * 400 `server` error + */ + 400: unknown; + /** + * 500 server error + */ + 500: unknown; +}; + +export type ComplexTypesResponses = { + /** + * Successful response + */ + 200: Array; +}; + +export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; + +export type MultipartResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multipart'; +}; + +export type MultipartResponseResponses = { + /** + * OK + */ + 200: { + file?: Blob | File; + metadata?: { + foo?: string; + bar?: string; + }; + }; +}; + +export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; + +export type MultipartRequestData = { + body?: { + content?: Blob | File; + data?: ModelWithString | null; + }; + path?: never; + query?: never; + url: '/api/v{api-version}/multipart'; +}; + +export type ComplexParamsData = { + body?: { + readonly key: string | null; + name: string | null; + enabled?: boolean; + type: 'Monkey' | 'Horse' | 'Bird'; + listOfModels?: Array | null; + listOfStrings?: Array | null; + parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; + readonly user?: { + readonly id?: number; + readonly name?: string | null; + }; + }; + path: { + id: number; + /** + * api-version should be required in standalone clients + */ + 'api-version': string; + }; + query?: never; + url: '/api/v{api-version}/complex/{id}'; +}; + +export type ComplexParamsResponses = { + /** + * Success + */ + 200: ModelWithString; +}; + +export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; + +export type CallWithResultFromHeaderData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/header'; +}; + +export type CallWithResultFromHeaderErrors = { + /** + * 400 server error + */ + 400: unknown; + /** + * 500 server error + */ + 500: unknown; +}; + +export type CallWithResultFromHeaderResponses = { + /** + * Successful response + */ + 200: unknown; +}; + +export type TestErrorCodeData = { + body?: never; + path?: never; + query: { + /** + * Status code to return + */ + status: number; + }; + url: '/api/v{api-version}/error'; +}; + +export type TestErrorCodeErrors = { + /** + * Custom message: Internal Server Error + */ + 500: unknown; + /** + * Custom message: Not Implemented + */ + 501: unknown; + /** + * Custom message: Bad Gateway + */ + 502: unknown; + /** + * Custom message: Service Unavailable + */ + 503: unknown; +}; + +export type TestErrorCodeResponses = { + /** + * Custom message: Successful response + */ + 200: unknown; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Data = { + body?: never; + path?: never; + query: { + /** + * Dummy input param + */ + nonAsciiParamæøåÆØÅöôêÊ: number; + }; + url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { + /** + * Successful response + */ + 200: Array; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; + +export type PutWithFormUrlEncodedData = { + body: ArrayWithStrings; + path?: never; + query?: never; + url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useMutation/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useMutation/@tanstack/react-query.gen.ts index 3bb1f02eec..bbc1eeb48a 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useMutation/@tanstack/react-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useMutation/@tanstack/react-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, useMutation, type UseMutationOptions } from '@tanstack/react-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, skipToken, useMutation, type UseMutationOptions, useQuery } from '@tanstack/react-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const exportOptions = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useExportQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(exportOptions, options); + export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -104,8 +120,8 @@ export const useFooWowMutation = (mutationOptions?: Partial) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -113,14 +129,18 @@ export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(apiVVersionODataControllerCountOptions, options); + export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -128,10 +148,14 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getApiVbyApiVersionSimpleOperationOptions, options); + export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -150,8 +174,8 @@ export const useDeleteCallWithoutParametersAndResponseMutation = (mutationOption export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -159,10 +183,14 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithoutParametersAndResponseOptions, options); + export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -299,8 +327,8 @@ export const useCallWithWeirdParameterNamesMutation = (mutationOptions?: Partial export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -308,8 +336,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -343,10 +371,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -361,10 +389,14 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithOptionalParamOptions, options); + export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -415,8 +447,8 @@ export const usePostApiVbyApiVersionFormDataMutation = (mutationOptions?: Partia export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -424,10 +456,14 @@ export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithDefaultParametersOptions, options); + export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -478,8 +514,8 @@ export const useDuplicateNameMutation = (mutationOptions?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -487,10 +523,14 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); +export const useDuplicateName2Query = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(duplicateName2Options, options); + export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -525,8 +565,8 @@ export const useDuplicateName4Mutation = (mutationOptions?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -534,14 +574,18 @@ export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithNoContentResponseOptions, options); + export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -549,14 +593,18 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseAndNoContentResponseOptions, options); + export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -564,14 +612,18 @@ export const dummyAOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyAOptions, options); + export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -579,14 +631,18 @@ export const dummyBOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyBOptions, options); + export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -594,10 +650,14 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); +export const useCallWithResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseOptions, options); + export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -632,8 +692,8 @@ export const useCallWithResponsesMutation = (mutationOptions?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -641,14 +701,18 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); +export const useCollectionFormatQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(collectionFormatOptions, options); + export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -656,10 +720,14 @@ export const typesOptions = (options: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(typesOptions, options); + export const uploadFileMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -678,8 +746,8 @@ export const useUploadFileMutation = (mutationOptions?: Partial) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -687,14 +755,18 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); +export const useFileResponseQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(fileResponseOptions, options); + export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -702,14 +774,18 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); +export const useComplexTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(complexTypesOptions, options); + export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -717,10 +793,14 @@ export const multipartResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(multipartResponseOptions, options); + export const multipartRequestMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/@tanstack/react-query.gen.ts new file mode 100644 index 0000000000..63173ae9d9 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/@tanstack/react-query.gen.ts @@ -0,0 +1,764 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, skipToken, type UseMutationOptions } from '@tanstack/react-query'; + +import { client } from '../client.gen'; +import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; +import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; + +export type QueryKey = [ + Pick & { + _id: string; + _infinite?: boolean; + tags?: ReadonlyArray; + } +]; + +const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ + QueryKey[0] +] => { + const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; + if (infinite) { + params._infinite = infinite; + } + if (tags) { + params.tags = tags; + } + if (options?.body) { + params.body = options.body; + } + if (options?.headers) { + params.headers = options.headers; + } + if (options?.path) { + params.path = options.path; + } + if (options?.query) { + params.query = options.query; + } + return [params]; +}; + +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + +export const exportQueryKey = (options?: Options) => createQueryKey('export', options); + +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await export_({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: exportQueryKey(resolveOptions(options)) +}); + +export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await patchApiVbyApiVersionNoTag({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const importMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await import_({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const fooWowMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await fooWow({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); + +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await apiVVersionODataControllerCount({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: apiVVersionODataControllerCountQueryKey(resolveOptions(options)) +}); + +export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); + +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await getApiVbyApiVersionSimpleOperation({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: getApiVbyApiVersionSimpleOperationQueryKey(resolveOptions(options)) +}); + +export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deleteCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); + +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await getCallWithoutParametersAndResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: getCallWithoutParametersAndResponseQueryKey(resolveOptions(options)) +}); + +export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await patchCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await putCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const deleteFooMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deleteFoo({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDescriptions({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * @deprecated + */ +export const deprecatedCallMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deprecatedCall({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithParametersMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithParameters({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithWeirdParameterNames({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); + +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await getCallWithOptionalParam({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: getCallWithOptionalParamQueryKey(resolveOptions(options)) +}); + +const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { + const params = { ...queryKey[0] }; + if (page.body) { + params.body = { + ...queryKey[0].body as any, + ...page.body as any + }; + } + if (page.headers) { + params.headers = { + ...queryKey[0].headers, + ...page.headers + }; + } + if (page.path) { + params.path = { + ...queryKey[0].path as any, + ...page.path as any + }; + } + if (page.query) { + params.query = { + ...queryKey[0].query as any, + ...page.query as any + }; + } + return params as unknown as typeof page; +}; + +export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); + +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +// @ts-ignore +{ + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { + // @ts-ignore + const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { + query: { + page: pageParam + } + }; + const params = createInfiniteParams(queryKey, page); + const { data } = await getCallWithOptionalParam({ + ...options, + ...params, + signal, + throwOnError: true + }); + return data; + }), + queryKey: getCallWithOptionalParamInfiniteQueryKey(resolveOptions(options)) +}); + +export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postCallWithOptionalParam({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postApiVbyApiVersionRequestBody({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postApiVbyApiVersionFormData({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); + +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithDefaultParameters({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithDefaultParametersQueryKey(resolveOptions(options)) +}); + +export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDefaultOptionalParameters({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callToTestOrderOfParams({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateNameMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); + +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await duplicateName2({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) +}); + +export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName3({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName4({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); + +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithNoContentResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithNoContentResponseQueryKey(resolveOptions(options)) +}); + +export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); + +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithResponseAndNoContentResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithResponseAndNoContentResponseQueryKey(resolveOptions(options)) +}); + +export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); + +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await dummyA({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: dummyAQueryKey(resolveOptions(options)) +}); + +export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); + +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await dummyB({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: dummyBQueryKey(resolveOptions(options)) +}); + +export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); + +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) +}); + +export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDuplicateResponses({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithResponses({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); + +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await collectionFormat({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) +}); + +export const typesQueryKey = (options: Options) => createQueryKey('types', options); + +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await types({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: typesQueryKey(resolveOptions(options)) +}); + +export const uploadFileMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await uploadFile({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); + +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await fileResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) +}); + +export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); + +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await complexTypes({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) +}); + +export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); + +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await multipartResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: multipartResponseQueryKey(resolveOptions(options)) +}); + +export const multipartRequestMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await multipartRequest({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const complexParamsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await complexParams({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithResultFromHeader({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await testErrorCode({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * Login User + */ +export const putWithFormUrlEncodedMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await putWithFormUrlEncoded({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/client.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/client.gen.ts new file mode 100644 index 0000000000..25cd14eafb --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/client.gen.ts @@ -0,0 +1,16 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type ClientOptions, type Config, createClient, createConfig } from './client'; +import type { ClientOptions as ClientOptions2 } from './types.gen'; + +/** + * The `createClientConfig()` function will be called on client initialization + * and the returned object will become the client's initial configuration. + * + * You may want to initialize your client this way instead of calling + * `setConfig()`. This is useful for example if you're using Next.js + * to ensure your client always has the correct values. + */ +export type CreateClientConfig = (override?: Config) => Config & T>; + +export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/client.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/client.gen.ts new file mode 100644 index 0000000000..14dc0a0ec5 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/client.gen.ts @@ -0,0 +1,290 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { createSseClient } from '../core/serverSentEvents.gen'; +import type { HttpMethod } from '../core/types.gen'; +import { getValidRequestBody } from '../core/utils.gen'; +import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; +import { + buildUrl, + createConfig, + createInterceptors, + getParseAs, + mergeConfigs, + mergeHeaders, + setAuthParams, +} from './utils.gen'; + +type ReqInit = Omit & { + body?: any; + headers: ReturnType; +}; + +export const createClient = (config: Config = {}): Client => { + let _config = mergeConfigs(createConfig(), config); + + const getConfig = (): Config => ({ ..._config }); + + const setConfig = (config: Config): Config => { + _config = mergeConfigs(_config, config); + return getConfig(); + }; + + const interceptors = createInterceptors(); + + const beforeRequest = async (options: RequestOptions) => { + const opts = { + ..._config, + ...options, + fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, + headers: mergeHeaders(_config.headers, options.headers), + serializedBody: undefined as string | undefined, + }; + + if (opts.security) { + await setAuthParams({ + ...opts, + security: opts.security, + }); + } + + if (opts.requestValidator) { + await opts.requestValidator(opts); + } + + if (opts.body !== undefined && opts.bodySerializer) { + opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; + } + + // remove Content-Type header if body is empty to avoid sending invalid requests + if (opts.body === undefined || opts.serializedBody === '') { + opts.headers.delete('Content-Type'); + } + + const url = buildUrl(opts); + + return { opts, url }; + }; + + const request: Client['request'] = async (options) => { + // @ts-expect-error + const { opts, url } = await beforeRequest(options); + const requestInit: ReqInit = { + redirect: 'follow', + ...opts, + body: getValidRequestBody(opts), + }; + + let request = new Request(url, requestInit); + + for (const fn of interceptors.request.fns) { + if (fn) { + request = await fn(request, opts); + } + } + + // fetch must be assigned here, otherwise it would throw the error: + // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation + const _fetch = opts.fetch!; + let response: Response; + + try { + response = await _fetch(request); + } catch (error) { + // Handle fetch exceptions (AbortError, network errors, etc.) + let finalError = error; + + for (const fn of interceptors.error.fns) { + if (fn) { + finalError = (await fn(error, undefined as any, request, opts)) as unknown; + } + } + + finalError = finalError || ({} as unknown); + + if (opts.throwOnError) { + throw finalError; + } + + // Return error response + return opts.responseStyle === 'data' + ? undefined + : { + error: finalError, + request, + response: undefined as any, + }; + } + + for (const fn of interceptors.response.fns) { + if (fn) { + response = await fn(response, request, opts); + } + } + + const result = { + request, + response, + }; + + if (response.ok) { + const parseAs = + (opts.parseAs === 'auto' + ? getParseAs(response.headers.get('Content-Type')) + : opts.parseAs) ?? 'json'; + + if (response.status === 204 || response.headers.get('Content-Length') === '0') { + let emptyData: any; + switch (parseAs) { + case 'arrayBuffer': + case 'blob': + case 'text': + emptyData = await response[parseAs](); + break; + case 'formData': + emptyData = new FormData(); + break; + case 'stream': + emptyData = response.body; + break; + case 'json': + default: + emptyData = {}; + break; + } + return opts.responseStyle === 'data' + ? emptyData + : { + data: emptyData, + ...result, + }; + } + + let data: any; + switch (parseAs) { + case 'arrayBuffer': + case 'blob': + case 'formData': + case 'text': + data = await response[parseAs](); + break; + case 'json': { + // Some servers return 200 with no Content-Length and empty body. + // response.json() would throw; read as text and parse if non-empty. + const text = await response.text(); + data = text ? JSON.parse(text) : {}; + break; + } + case 'stream': + return opts.responseStyle === 'data' + ? response.body + : { + data: response.body, + ...result, + }; + } + + if (parseAs === 'json') { + if (opts.responseValidator) { + await opts.responseValidator(data); + } + + if (opts.responseTransformer) { + data = await opts.responseTransformer(data); + } + } + + return opts.responseStyle === 'data' + ? data + : { + data, + ...result, + }; + } + + const textError = await response.text(); + let jsonError: unknown; + + try { + jsonError = JSON.parse(textError); + } catch { + // noop + } + + const error = jsonError ?? textError; + let finalError = error; + + for (const fn of interceptors.error.fns) { + if (fn) { + finalError = (await fn(error, response, request, opts)) as string; + } + } + + finalError = finalError || ({} as string); + + if (opts.throwOnError) { + throw finalError; + } + + // TODO: we probably want to return error and improve types + return opts.responseStyle === 'data' + ? undefined + : { + error: finalError, + ...result, + }; + }; + + const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => + request({ ...options, method }); + + const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { + const { opts, url } = await beforeRequest(options); + return createSseClient({ + ...opts, + body: opts.body as BodyInit | null | undefined, + headers: opts.headers as unknown as Record, + method, + onRequest: async (url, init) => { + let request = new Request(url, init); + for (const fn of interceptors.request.fns) { + if (fn) { + request = await fn(request, opts); + } + } + return request; + }, + serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, + url, + }); + }; + + const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); + + return { + buildUrl: _buildUrl, + connect: makeMethodFn('CONNECT'), + delete: makeMethodFn('DELETE'), + get: makeMethodFn('GET'), + getConfig, + head: makeMethodFn('HEAD'), + interceptors, + options: makeMethodFn('OPTIONS'), + patch: makeMethodFn('PATCH'), + post: makeMethodFn('POST'), + put: makeMethodFn('PUT'), + request, + setConfig, + sse: { + connect: makeSseFn('CONNECT'), + delete: makeSseFn('DELETE'), + get: makeSseFn('GET'), + head: makeSseFn('HEAD'), + options: makeSseFn('OPTIONS'), + patch: makeSseFn('PATCH'), + post: makeSseFn('POST'), + put: makeSseFn('PUT'), + trace: makeSseFn('TRACE'), + }, + trace: makeMethodFn('TRACE'), + } as Client; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/index.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/index.ts new file mode 100644 index 0000000000..b295edeca0 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/index.ts @@ -0,0 +1,25 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type { Auth } from '../core/auth.gen'; +export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; +export { + formDataBodySerializer, + jsonBodySerializer, + urlSearchParamsBodySerializer, +} from '../core/bodySerializer.gen'; +export { buildClientParams } from '../core/params.gen'; +export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; +export { createClient } from './client.gen'; +export type { + Client, + ClientOptions, + Config, + CreateClientConfig, + Options, + RequestOptions, + RequestResult, + ResolvedRequestOptions, + ResponseStyle, + TDataShape, +} from './types.gen'; +export { createConfig, mergeHeaders } from './utils.gen'; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/types.gen.ts new file mode 100644 index 0000000000..a3f8616511 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/types.gen.ts @@ -0,0 +1,214 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Auth } from '../core/auth.gen'; +import type { + ServerSentEventsOptions, + ServerSentEventsResult, +} from '../core/serverSentEvents.gen'; +import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; +import type { Middleware } from './utils.gen'; + +export type ResponseStyle = 'data' | 'fields'; + +export interface Config + extends Omit, CoreConfig { + /** + * Base URL for all requests made by this client. + */ + baseUrl?: T['baseUrl']; + /** + * Fetch API implementation. You can use this option to provide a custom + * fetch instance. + * + * @default globalThis.fetch + */ + fetch?: typeof fetch; + /** + * Please don't use the Fetch client for Next.js applications. The `next` + * options won't have any effect. + * + * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. + */ + next?: never; + /** + * Return the response data parsed in a specified format. By default, `auto` + * will infer the appropriate method from the `Content-Type` response header. + * You can override this behavior with any of the {@link Body} methods. + * Select `stream` if you don't want to parse response data at all. + * + * @default 'auto' + */ + parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; + /** + * Should we return only data or multiple fields (data, error, response, etc.)? + * + * @default 'fields' + */ + responseStyle?: ResponseStyle; + /** + * Throw an error instead of returning it in the response? + * + * @default false + */ + throwOnError?: T['throwOnError']; +} + +export interface RequestOptions< + TData = unknown, + TResponseStyle extends ResponseStyle = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, +> + extends + Config<{ + responseStyle: TResponseStyle; + throwOnError: ThrowOnError; + }>, + Pick< + ServerSentEventsOptions, + | 'onRequest' + | 'onSseError' + | 'onSseEvent' + | 'sseDefaultRetryDelay' + | 'sseMaxRetryAttempts' + | 'sseMaxRetryDelay' + > { + /** + * Any body that you want to add to your request. + * + * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} + */ + body?: unknown; + path?: Record; + query?: Record; + /** + * Security mechanism(s) to use for the request. + */ + security?: ReadonlyArray; + url: Url; +} + +export interface ResolvedRequestOptions< + TResponseStyle extends ResponseStyle = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, +> extends RequestOptions { + serializedBody?: string; +} + +export type RequestResult< + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = boolean, + TResponseStyle extends ResponseStyle = 'fields', +> = ThrowOnError extends true + ? Promise< + TResponseStyle extends 'data' + ? TData extends Record + ? TData[keyof TData] + : TData + : { + data: TData extends Record ? TData[keyof TData] : TData; + request: Request; + response: Response; + } + > + : Promise< + TResponseStyle extends 'data' + ? (TData extends Record ? TData[keyof TData] : TData) | undefined + : ( + | { + data: TData extends Record ? TData[keyof TData] : TData; + error: undefined; + } + | { + data: undefined; + error: TError extends Record ? TError[keyof TError] : TError; + } + ) & { + request: Request; + response: Response; + } + >; + +export interface ClientOptions { + baseUrl?: string; + responseStyle?: ResponseStyle; + throwOnError?: boolean; +} + +type MethodFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'>, +) => RequestResult; + +type SseFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'>, +) => Promise>; + +type RequestFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'> & + Pick>, 'method'>, +) => RequestResult; + +type BuildUrlFn = < + TData extends { + body?: unknown; + path?: Record; + query?: Record; + url: string; + }, +>( + options: TData & Options, +) => string; + +export type Client = CoreClient & { + interceptors: Middleware; +}; + +/** + * The `createClientConfig()` function will be called on client initialization + * and the returned object will become the client's initial configuration. + * + * You may want to initialize your client this way instead of calling + * `setConfig()`. This is useful for example if you're using Next.js + * to ensure your client always has the correct values. + */ +export type CreateClientConfig = ( + override?: Config, +) => Config & T>; + +export interface TDataShape { + body?: unknown; + headers?: unknown; + path?: unknown; + query?: unknown; + url: string; +} + +type OmitKeys = Pick>; + +export type Options< + TData extends TDataShape = TDataShape, + ThrowOnError extends boolean = boolean, + TResponse = unknown, + TResponseStyle extends ResponseStyle = 'fields', +> = OmitKeys< + RequestOptions, + 'body' | 'path' | 'query' | 'url' +> & + ([TData] extends [never] ? unknown : Omit); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/utils.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/utils.gen.ts new file mode 100644 index 0000000000..b4bd2435ce --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/client/utils.gen.ts @@ -0,0 +1,316 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { getAuthToken } from '../core/auth.gen'; +import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; +import { jsonBodySerializer } from '../core/bodySerializer.gen'; +import { + serializeArrayParam, + serializeObjectParam, + serializePrimitiveParam, +} from '../core/pathSerializer.gen'; +import { getUrl } from '../core/utils.gen'; +import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; + +export const createQuerySerializer = ({ + parameters = {}, + ...args +}: QuerySerializerOptions = {}) => { + const querySerializer = (queryParams: T) => { + const search: string[] = []; + if (queryParams && typeof queryParams === 'object') { + for (const name in queryParams) { + const value = queryParams[name]; + + if (value === undefined || value === null) { + continue; + } + + const options = parameters[name] || args; + + if (Array.isArray(value)) { + const serializedArray = serializeArrayParam({ + allowReserved: options.allowReserved, + explode: true, + name, + style: 'form', + value, + ...options.array, + }); + if (serializedArray) search.push(serializedArray); + } else if (typeof value === 'object') { + const serializedObject = serializeObjectParam({ + allowReserved: options.allowReserved, + explode: true, + name, + style: 'deepObject', + value: value as Record, + ...options.object, + }); + if (serializedObject) search.push(serializedObject); + } else { + const serializedPrimitive = serializePrimitiveParam({ + allowReserved: options.allowReserved, + name, + value: value as string, + }); + if (serializedPrimitive) search.push(serializedPrimitive); + } + } + } + return search.join('&'); + }; + return querySerializer; +}; + +/** + * Infers parseAs value from provided Content-Type header. + */ +export const getParseAs = (contentType: string | null): Exclude => { + if (!contentType) { + // If no Content-Type header is provided, the best we can do is return the raw response body, + // which is effectively the same as the 'stream' option. + return 'stream'; + } + + const cleanContent = contentType.split(';')[0]?.trim(); + + if (!cleanContent) { + return; + } + + if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { + return 'json'; + } + + if (cleanContent === 'multipart/form-data') { + return 'formData'; + } + + if ( + ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) + ) { + return 'blob'; + } + + if (cleanContent.startsWith('text/')) { + return 'text'; + } + + return; +}; + +const checkForExistence = ( + options: Pick & { + headers: Headers; + }, + name?: string, +): boolean => { + if (!name) { + return false; + } + if ( + options.headers.has(name) || + options.query?.[name] || + options.headers.get('Cookie')?.includes(`${name}=`) + ) { + return true; + } + return false; +}; + +export const setAuthParams = async ({ + security, + ...options +}: Pick, 'security'> & + Pick & { + headers: Headers; + }) => { + for (const auth of security) { + if (checkForExistence(options, auth.name)) { + continue; + } + + const token = await getAuthToken(auth, options.auth); + + if (!token) { + continue; + } + + const name = auth.name ?? 'Authorization'; + + switch (auth.in) { + case 'query': + if (!options.query) { + options.query = {}; + } + options.query[name] = token; + break; + case 'cookie': + options.headers.append('Cookie', `${name}=${token}`); + break; + case 'header': + default: + options.headers.set(name, token); + break; + } + } +}; + +export const buildUrl: Client['buildUrl'] = (options) => + getUrl({ + baseUrl: options.baseUrl as string, + path: options.path, + query: options.query, + querySerializer: + typeof options.querySerializer === 'function' + ? options.querySerializer + : createQuerySerializer(options.querySerializer), + url: options.url, + }); + +export const mergeConfigs = (a: Config, b: Config): Config => { + const config = { ...a, ...b }; + if (config.baseUrl?.endsWith('/')) { + config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); + } + config.headers = mergeHeaders(a.headers, b.headers); + return config; +}; + +const headersEntries = (headers: Headers): Array<[string, string]> => { + const entries: Array<[string, string]> = []; + headers.forEach((value, key) => { + entries.push([key, value]); + }); + return entries; +}; + +export const mergeHeaders = ( + ...headers: Array['headers'] | undefined> +): Headers => { + const mergedHeaders = new Headers(); + for (const header of headers) { + if (!header) { + continue; + } + + const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); + + for (const [key, value] of iterator) { + if (value === null) { + mergedHeaders.delete(key); + } else if (Array.isArray(value)) { + for (const v of value) { + mergedHeaders.append(key, v as string); + } + } else if (value !== undefined) { + // assume object headers are meant to be JSON stringified, i.e. their + // content value in OpenAPI specification is 'application/json' + mergedHeaders.set( + key, + typeof value === 'object' ? JSON.stringify(value) : (value as string), + ); + } + } + } + return mergedHeaders; +}; + +type ErrInterceptor = ( + error: Err, + response: Res, + request: Req, + options: Options, +) => Err | Promise; + +type ReqInterceptor = (request: Req, options: Options) => Req | Promise; + +type ResInterceptor = ( + response: Res, + request: Req, + options: Options, +) => Res | Promise; + +class Interceptors { + fns: Array = []; + + clear(): void { + this.fns = []; + } + + eject(id: number | Interceptor): void { + const index = this.getInterceptorIndex(id); + if (this.fns[index]) { + this.fns[index] = null; + } + } + + exists(id: number | Interceptor): boolean { + const index = this.getInterceptorIndex(id); + return Boolean(this.fns[index]); + } + + getInterceptorIndex(id: number | Interceptor): number { + if (typeof id === 'number') { + return this.fns[id] ? id : -1; + } + return this.fns.indexOf(id); + } + + update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { + const index = this.getInterceptorIndex(id); + if (this.fns[index]) { + this.fns[index] = fn; + return id; + } + return false; + } + + use(fn: Interceptor): number { + this.fns.push(fn); + return this.fns.length - 1; + } +} + +export interface Middleware { + error: Interceptors>; + request: Interceptors>; + response: Interceptors>; +} + +export const createInterceptors = (): Middleware< + Req, + Res, + Err, + Options +> => ({ + error: new Interceptors>(), + request: new Interceptors>(), + response: new Interceptors>(), +}); + +const defaultQuerySerializer = createQuerySerializer({ + allowReserved: false, + array: { + explode: true, + style: 'form', + }, + object: { + explode: true, + style: 'deepObject', + }, +}); + +const defaultHeaders = { + 'Content-Type': 'application/json', +}; + +export const createConfig = ( + override: Config & T> = {}, +): Config & T> => ({ + ...jsonBodySerializer, + headers: defaultHeaders, + parseAs: 'auto', + querySerializer: defaultQuerySerializer, + ...override, +}); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/auth.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/auth.gen.ts new file mode 100644 index 0000000000..3ebf994788 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/auth.gen.ts @@ -0,0 +1,41 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type AuthToken = string | undefined; + +export interface Auth { + /** + * Which part of the request do we use to send the auth? + * + * @default 'header' + */ + in?: 'header' | 'query' | 'cookie'; + /** + * Header or query parameter name. + * + * @default 'Authorization' + */ + name?: string; + scheme?: 'basic' | 'bearer'; + type: 'apiKey' | 'http'; +} + +export const getAuthToken = async ( + auth: Auth, + callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, +): Promise => { + const token = typeof callback === 'function' ? await callback(auth) : callback; + + if (!token) { + return; + } + + if (auth.scheme === 'bearer') { + return `Bearer ${token}`; + } + + if (auth.scheme === 'basic') { + return `Basic ${btoa(token)}`; + } + + return token; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/bodySerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/bodySerializer.gen.ts new file mode 100644 index 0000000000..67daca60f8 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/bodySerializer.gen.ts @@ -0,0 +1,82 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; + +export type QuerySerializer = (query: Record) => string; + +export type BodySerializer = (body: unknown) => unknown; + +type QuerySerializerOptionsObject = { + allowReserved?: boolean; + array?: Partial>; + object?: Partial>; +}; + +export type QuerySerializerOptions = QuerySerializerOptionsObject & { + /** + * Per-parameter serialization overrides. When provided, these settings + * override the global array/object settings for specific parameter names. + */ + parameters?: Record; +}; + +const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { + if (typeof value === 'string' || value instanceof Blob) { + data.append(key, value); + } else if (value instanceof Date) { + data.append(key, value.toISOString()); + } else { + data.append(key, JSON.stringify(value)); + } +}; + +const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { + if (typeof value === 'string') { + data.append(key, value); + } else { + data.append(key, JSON.stringify(value)); + } +}; + +export const formDataBodySerializer = { + bodySerializer: (body: unknown): FormData => { + const data = new FormData(); + + Object.entries(body as Record).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + if (Array.isArray(value)) { + value.forEach((v) => serializeFormDataPair(data, key, v)); + } else { + serializeFormDataPair(data, key, value); + } + }); + + return data; + }, +}; + +export const jsonBodySerializer = { + bodySerializer: (body: unknown): string => + JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), +}; + +export const urlSearchParamsBodySerializer = { + bodySerializer: (body: unknown): string => { + const data = new URLSearchParams(); + + Object.entries(body as Record).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + if (Array.isArray(value)) { + value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); + } else { + serializeUrlSearchParamsPair(data, key, value); + } + }); + + return data.toString(); + }, +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/params.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/params.gen.ts new file mode 100644 index 0000000000..7955601a5c --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/params.gen.ts @@ -0,0 +1,169 @@ +// This file is auto-generated by @hey-api/openapi-ts + +type Slot = 'body' | 'headers' | 'path' | 'query'; + +export type Field = + | { + in: Exclude; + /** + * Field name. This is the name we want the user to see and use. + */ + key: string; + /** + * Field mapped name. This is the name we want to use in the request. + * If omitted, we use the same value as `key`. + */ + map?: string; + } + | { + in: Extract; + /** + * Key isn't required for bodies. + */ + key?: string; + map?: string; + } + | { + /** + * Field name. This is the name we want the user to see and use. + */ + key: string; + /** + * Field mapped name. This is the name we want to use in the request. + * If `in` is omitted, `map` aliases `key` to the transport layer. + */ + map: Slot; + }; + +export interface Fields { + allowExtra?: Partial>; + args?: ReadonlyArray; +} + +export type FieldsConfig = ReadonlyArray; + +const extraPrefixesMap: Record = { + $body_: 'body', + $headers_: 'headers', + $path_: 'path', + $query_: 'query', +}; +const extraPrefixes = Object.entries(extraPrefixesMap); + +type KeyMap = Map< + string, + | { + in: Slot; + map?: string; + } + | { + in?: never; + map: Slot; + } +>; + +const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { + if (!map) { + map = new Map(); + } + + for (const config of fields) { + if ('in' in config) { + if (config.key) { + map.set(config.key, { + in: config.in, + map: config.map, + }); + } + } else if ('key' in config) { + map.set(config.key, { + map: config.map, + }); + } else if (config.args) { + buildKeyMap(config.args, map); + } + } + + return map; +}; + +interface Params { + body: unknown; + headers: Record; + path: Record; + query: Record; +} + +const stripEmptySlots = (params: Params) => { + for (const [slot, value] of Object.entries(params)) { + if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { + delete params[slot as Slot]; + } + } +}; + +export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { + const params: Params = { + body: {}, + headers: {}, + path: {}, + query: {}, + }; + + const map = buildKeyMap(fields); + + let config: FieldsConfig[number] | undefined; + + for (const [index, arg] of args.entries()) { + if (fields[index]) { + config = fields[index]; + } + + if (!config) { + continue; + } + + if ('in' in config) { + if (config.key) { + const field = map.get(config.key)!; + const name = field.map || config.key; + if (field.in) { + (params[field.in] as Record)[name] = arg; + } + } else { + params.body = arg; + } + } else { + for (const [key, value] of Object.entries(arg ?? {})) { + const field = map.get(key); + + if (field) { + if (field.in) { + const name = field.map || key; + (params[field.in] as Record)[name] = value; + } else { + params[field.map] = value; + } + } else { + const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); + + if (extra) { + const [prefix, slot] = extra; + (params[slot] as Record)[key.slice(prefix.length)] = value; + } else if ('allowExtra' in config && config.allowExtra) { + for (const [slot, allowed] of Object.entries(config.allowExtra)) { + if (allowed) { + (params[slot as Slot] as Record)[key] = value; + break; + } + } + } + } + } + } + } + + stripEmptySlots(params); + + return params; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/pathSerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/pathSerializer.gen.ts new file mode 100644 index 0000000000..994b2848c6 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/pathSerializer.gen.ts @@ -0,0 +1,171 @@ +// This file is auto-generated by @hey-api/openapi-ts + +interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} + +interface SerializePrimitiveOptions { + allowReserved?: boolean; + name: string; +} + +export interface SerializerOptions { + /** + * @default true + */ + explode: boolean; + style: T; +} + +export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; +export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; +type MatrixStyle = 'label' | 'matrix' | 'simple'; +export type ObjectStyle = 'form' | 'deepObject'; +type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; + +interface SerializePrimitiveParam extends SerializePrimitiveOptions { + value: string; +} + +export const separatorArrayExplode = (style: ArraySeparatorStyle) => { + switch (style) { + case 'label': + return '.'; + case 'matrix': + return ';'; + case 'simple': + return ','; + default: + return '&'; + } +}; + +export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { + switch (style) { + case 'form': + return ','; + case 'pipeDelimited': + return '|'; + case 'spaceDelimited': + return '%20'; + default: + return ','; + } +}; + +export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { + switch (style) { + case 'label': + return '.'; + case 'matrix': + return ';'; + case 'simple': + return ','; + default: + return '&'; + } +}; + +export const serializeArrayParam = ({ + allowReserved, + explode, + name, + style, + value, +}: SerializeOptions & { + value: unknown[]; +}) => { + if (!explode) { + const joinedValues = ( + allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) + ).join(separatorArrayNoExplode(style)); + switch (style) { + case 'label': + return `.${joinedValues}`; + case 'matrix': + return `;${name}=${joinedValues}`; + case 'simple': + return joinedValues; + default: + return `${name}=${joinedValues}`; + } + } + + const separator = separatorArrayExplode(style); + const joinedValues = value + .map((v) => { + if (style === 'label' || style === 'simple') { + return allowReserved ? v : encodeURIComponent(v as string); + } + + return serializePrimitiveParam({ + allowReserved, + name, + value: v as string, + }); + }) + .join(separator); + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; +}; + +export const serializePrimitiveParam = ({ + allowReserved, + name, + value, +}: SerializePrimitiveParam) => { + if (value === undefined || value === null) { + return ''; + } + + if (typeof value === 'object') { + throw new Error( + 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', + ); + } + + return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; +}; + +export const serializeObjectParam = ({ + allowReserved, + explode, + name, + style, + value, + valueOnly, +}: SerializeOptions & { + value: Record | Date; + valueOnly?: boolean; +}) => { + if (value instanceof Date) { + return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; + } + + if (style !== 'deepObject' && !explode) { + let values: string[] = []; + Object.entries(value).forEach(([key, v]) => { + values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; + }); + const joinedValues = values.join(','); + switch (style) { + case 'form': + return `${name}=${joinedValues}`; + case 'label': + return `.${joinedValues}`; + case 'matrix': + return `;${name}=${joinedValues}`; + default: + return joinedValues; + } + } + + const separator = separatorObjectExplode(style); + const joinedValues = Object.entries(value) + .map(([key, v]) => + serializePrimitiveParam({ + allowReserved, + name: style === 'deepObject' ? `${name}[${key}]` : key, + value: v as string, + }), + ) + .join(separator); + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/queryKeySerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/queryKeySerializer.gen.ts new file mode 100644 index 0000000000..5000df606f --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/queryKeySerializer.gen.ts @@ -0,0 +1,117 @@ +// This file is auto-generated by @hey-api/openapi-ts + +/** + * JSON-friendly union that mirrors what Pinia Colada can hash. + */ +export type JsonValue = + | null + | string + | number + | boolean + | JsonValue[] + | { [key: string]: JsonValue }; + +/** + * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. + */ +export const queryKeyJsonReplacer = (_key: string, value: unknown) => { + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { + return undefined; + } + if (typeof value === 'bigint') { + return value.toString(); + } + if (value instanceof Date) { + return value.toISOString(); + } + return value; +}; + +/** + * Safely stringifies a value and parses it back into a JsonValue. + */ +export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { + try { + const json = JSON.stringify(input, queryKeyJsonReplacer); + if (json === undefined) { + return undefined; + } + return JSON.parse(json) as JsonValue; + } catch { + return undefined; + } +}; + +/** + * Detects plain objects (including objects with a null prototype). + */ +const isPlainObject = (value: unknown): value is Record => { + if (value === null || typeof value !== 'object') { + return false; + } + const prototype = Object.getPrototypeOf(value as object); + return prototype === Object.prototype || prototype === null; +}; + +/** + * Turns URLSearchParams into a sorted JSON object for deterministic keys. + */ +const serializeSearchParams = (params: URLSearchParams): JsonValue => { + const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); + const result: Record = {}; + + for (const [key, value] of entries) { + const existing = result[key]; + if (existing === undefined) { + result[key] = value; + continue; + } + + if (Array.isArray(existing)) { + (existing as string[]).push(value); + } else { + result[key] = [existing, value]; + } + } + + return result; +}; + +/** + * Normalizes any accepted value into a JSON-friendly shape for query keys. + */ +export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { + if (value === null) { + return null; + } + + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return value; + } + + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { + return undefined; + } + + if (typeof value === 'bigint') { + return value.toString(); + } + + if (value instanceof Date) { + return value.toISOString(); + } + + if (Array.isArray(value)) { + return stringifyToJsonValue(value); + } + + if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { + return serializeSearchParams(value); + } + + if (isPlainObject(value)) { + return stringifyToJsonValue(value); + } + + return undefined; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/serverSentEvents.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/serverSentEvents.gen.ts new file mode 100644 index 0000000000..6aa6cf02a4 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/serverSentEvents.gen.ts @@ -0,0 +1,243 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Config } from './types.gen'; + +export type ServerSentEventsOptions = Omit & + Pick & { + /** + * Fetch API implementation. You can use this option to provide a custom + * fetch instance. + * + * @default globalThis.fetch + */ + fetch?: typeof fetch; + /** + * Implementing clients can call request interceptors inside this hook. + */ + onRequest?: (url: string, init: RequestInit) => Promise; + /** + * Callback invoked when a network or parsing error occurs during streaming. + * + * This option applies only if the endpoint returns a stream of events. + * + * @param error The error that occurred. + */ + onSseError?: (error: unknown) => void; + /** + * Callback invoked when an event is streamed from the server. + * + * This option applies only if the endpoint returns a stream of events. + * + * @param event Event streamed from the server. + * @returns Nothing (void). + */ + onSseEvent?: (event: StreamEvent) => void; + serializedBody?: RequestInit['body']; + /** + * Default retry delay in milliseconds. + * + * This option applies only if the endpoint returns a stream of events. + * + * @default 3000 + */ + sseDefaultRetryDelay?: number; + /** + * Maximum number of retry attempts before giving up. + */ + sseMaxRetryAttempts?: number; + /** + * Maximum retry delay in milliseconds. + * + * Applies only when exponential backoff is used. + * + * This option applies only if the endpoint returns a stream of events. + * + * @default 30000 + */ + sseMaxRetryDelay?: number; + /** + * Optional sleep function for retry backoff. + * + * Defaults to using `setTimeout`. + */ + sseSleepFn?: (ms: number) => Promise; + url: string; + }; + +export interface StreamEvent { + data: TData; + event?: string; + id?: string; + retry?: number; +} + +export type ServerSentEventsResult = { + stream: AsyncGenerator< + TData extends Record ? TData[keyof TData] : TData, + TReturn, + TNext + >; +}; + +export const createSseClient = ({ + onRequest, + onSseError, + onSseEvent, + responseTransformer, + responseValidator, + sseDefaultRetryDelay, + sseMaxRetryAttempts, + sseMaxRetryDelay, + sseSleepFn, + url, + ...options +}: ServerSentEventsOptions): ServerSentEventsResult => { + let lastEventId: string | undefined; + + const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + + const createStream = async function* () { + let retryDelay: number = sseDefaultRetryDelay ?? 3000; + let attempt = 0; + const signal = options.signal ?? new AbortController().signal; + + while (true) { + if (signal.aborted) break; + + attempt++; + + const headers = + options.headers instanceof Headers + ? options.headers + : new Headers(options.headers as Record | undefined); + + if (lastEventId !== undefined) { + headers.set('Last-Event-ID', lastEventId); + } + + try { + const requestInit: RequestInit = { + redirect: 'follow', + ...options, + body: options.serializedBody, + headers, + signal, + }; + let request = new Request(url, requestInit); + if (onRequest) { + request = await onRequest(url, requestInit); + } + // fetch must be assigned here, otherwise it would throw the error: + // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation + const _fetch = options.fetch ?? globalThis.fetch; + const response = await _fetch(request); + + if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); + + if (!response.body) throw new Error('No body in SSE response'); + + const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); + + let buffer = ''; + + const abortHandler = () => { + try { + reader.cancel(); + } catch { + // noop + } + }; + + signal.addEventListener('abort', abortHandler); + + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + buffer += value; + // Normalize line endings: CRLF -> LF, then CR -> LF + buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); + + const chunks = buffer.split('\n\n'); + buffer = chunks.pop() ?? ''; + + for (const chunk of chunks) { + const lines = chunk.split('\n'); + const dataLines: Array = []; + let eventName: string | undefined; + + for (const line of lines) { + if (line.startsWith('data:')) { + dataLines.push(line.replace(/^data:\s*/, '')); + } else if (line.startsWith('event:')) { + eventName = line.replace(/^event:\s*/, ''); + } else if (line.startsWith('id:')) { + lastEventId = line.replace(/^id:\s*/, ''); + } else if (line.startsWith('retry:')) { + const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); + if (!Number.isNaN(parsed)) { + retryDelay = parsed; + } + } + } + + let data: unknown; + let parsedJson = false; + + if (dataLines.length) { + const rawData = dataLines.join('\n'); + try { + data = JSON.parse(rawData); + parsedJson = true; + } catch { + data = rawData; + } + } + + if (parsedJson) { + if (responseValidator) { + await responseValidator(data); + } + + if (responseTransformer) { + data = await responseTransformer(data); + } + } + + onSseEvent?.({ + data, + event: eventName, + id: lastEventId, + retry: retryDelay, + }); + + if (dataLines.length) { + yield data as any; + } + } + } + } finally { + signal.removeEventListener('abort', abortHandler); + reader.releaseLock(); + } + + break; // exit loop on normal completion + } catch (error) { + // connection failed or aborted; retry after delay + onSseError?.(error); + + if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { + break; // stop after firing error + } + + // exponential backoff: double retry each attempt, cap at 30s + const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); + await sleep(backoff); + } + } + }; + + const stream = createStream(); + + return { stream }; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/types.gen.ts new file mode 100644 index 0000000000..97463257e4 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/types.gen.ts @@ -0,0 +1,104 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Auth, AuthToken } from './auth.gen'; +import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; + +export type HttpMethod = + | 'connect' + | 'delete' + | 'get' + | 'head' + | 'options' + | 'patch' + | 'post' + | 'put' + | 'trace'; + +export type Client< + RequestFn = never, + Config = unknown, + MethodFn = never, + BuildUrlFn = never, + SseFn = never, +> = { + /** + * Returns the final request URL. + */ + buildUrl: BuildUrlFn; + getConfig: () => Config; + request: RequestFn; + setConfig: (config: Config) => Config; +} & { + [K in HttpMethod]: MethodFn; +} & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); + +export interface Config { + /** + * Auth token or a function returning auth token. The resolved value will be + * added to the request payload as defined by its `security` array. + */ + auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; + /** + * A function for serializing request body parameter. By default, + * {@link JSON.stringify()} will be used. + */ + bodySerializer?: BodySerializer | null; + /** + * An object containing any HTTP headers that you want to pre-populate your + * `Headers` object with. + * + * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} + */ + headers?: + | RequestInit['headers'] + | Record< + string, + string | number | boolean | (string | number | boolean)[] | null | undefined | unknown + >; + /** + * The request method. + * + * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} + */ + method?: Uppercase; + /** + * A function for serializing request query parameters. By default, arrays + * will be exploded in form style, objects will be exploded in deepObject + * style, and reserved characters are percent-encoded. + * + * This method will have no effect if the native `paramsSerializer()` Axios + * API function is used. + * + * {@link https://swagger.io/docs/specification/serialization/#query View examples} + */ + querySerializer?: QuerySerializer | QuerySerializerOptions; + /** + * A function validating request data. This is useful if you want to ensure + * the request conforms to the desired shape, so it can be safely sent to + * the server. + */ + requestValidator?: (data: unknown) => Promise; + /** + * A function transforming response data before it's returned. This is useful + * for post-processing data, e.g. converting ISO strings into Date objects. + */ + responseTransformer?: (data: unknown) => Promise; + /** + * A function validating response data. This is useful if you want to ensure + * the response conforms to the desired shape, so it can be safely passed to + * the transformers and returned to the user. + */ + responseValidator?: (data: unknown) => Promise; +} + +type IsExactlyNeverOrNeverUndefined = [T] extends [never] + ? true + : [T] extends [never | undefined] + ? [undefined] extends [T] + ? false + : true + : false; + +export type OmitNever> = { + [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/utils.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/utils.gen.ts new file mode 100644 index 0000000000..e7ddbe3541 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/core/utils.gen.ts @@ -0,0 +1,140 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; +import { + type ArraySeparatorStyle, + serializeArrayParam, + serializeObjectParam, + serializePrimitiveParam, +} from './pathSerializer.gen'; + +export interface PathSerializer { + path: Record; + url: string; +} + +export const PATH_PARAM_RE = /\{[^{}]+\}/g; + +export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { + let url = _url; + const matches = _url.match(PATH_PARAM_RE); + if (matches) { + for (const match of matches) { + let explode = false; + let name = match.substring(1, match.length - 1); + let style: ArraySeparatorStyle = 'simple'; + + if (name.endsWith('*')) { + explode = true; + name = name.substring(0, name.length - 1); + } + + if (name.startsWith('.')) { + name = name.substring(1); + style = 'label'; + } else if (name.startsWith(';')) { + name = name.substring(1); + style = 'matrix'; + } + + const value = path[name]; + + if (value === undefined || value === null) { + continue; + } + + if (Array.isArray(value)) { + url = url.replace(match, serializeArrayParam({ explode, name, style, value })); + continue; + } + + if (typeof value === 'object') { + url = url.replace( + match, + serializeObjectParam({ + explode, + name, + style, + value: value as Record, + valueOnly: true, + }), + ); + continue; + } + + if (style === 'matrix') { + url = url.replace( + match, + `;${serializePrimitiveParam({ + name, + value: value as string, + })}`, + ); + continue; + } + + const replaceValue = encodeURIComponent( + style === 'label' ? `.${value as string}` : (value as string), + ); + url = url.replace(match, replaceValue); + } + } + return url; +}; + +export const getUrl = ({ + baseUrl, + path, + query, + querySerializer, + url: _url, +}: { + baseUrl?: string; + path?: Record; + query?: Record; + querySerializer: QuerySerializer; + url: string; +}) => { + const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; + let url = (baseUrl ?? '') + pathUrl; + if (path) { + url = defaultPathSerializer({ path, url }); + } + let search = query ? querySerializer(query) : ''; + if (search.startsWith('?')) { + search = search.substring(1); + } + if (search) { + url += `?${search}`; + } + return url; +}; + +export function getValidRequestBody(options: { + body?: unknown; + bodySerializer?: BodySerializer | null; + serializedBody?: unknown; +}) { + const hasBody = options.body !== undefined; + const isSerializedBody = hasBody && options.bodySerializer; + + if (isSerializedBody) { + if ('serializedBody' in options) { + const hasSerializedBody = + options.serializedBody !== undefined && options.serializedBody !== ''; + + return hasSerializedBody ? options.serializedBody : null; + } + + // not all clients implement a serializedBody property (i.e. client-axios) + return options.body !== '' ? options.body : null; + } + + // plain/text body + if (hasBody) { + return options.body; + } + + // no body was provided + return undefined; +} diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/index.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/index.ts new file mode 100644 index 0000000000..6e132194fd --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/index.ts @@ -0,0 +1,4 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; +export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/sdk.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/sdk.gen.ts new file mode 100644 index 0000000000..e48dcff8cf --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/sdk.gen.ts @@ -0,0 +1,206 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; +import { client } from './client.gen'; +import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; + +export type Options = Options2 & { + /** + * You can provide a client instance returned by `createClient()` instead of + * individual options. This might be also useful if you want to implement a + * custom client. + */ + client?: Client; + /** + * You can pass arbitrary values through the `meta` object. This can be + * used to access values that aren't defined as part of the SDK function. + */ + meta?: Record; +}; + +export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); + +export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); + +export const import_ = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/no+tag', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); + +export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); + +export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); + +export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); + +export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); + +export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); + +export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); + +export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); + +export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); + +export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); + +export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); + +export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); + +/** + * @deprecated + */ +export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); + +export const callWithParameters = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/parameters/{parameterPath}', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ + url: '/api/v{api-version}/parameters', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/parameters', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ + url: '/api/v{api-version}/requestBody', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options?.headers + } +}); + +export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ + ...formDataBodySerializer, + url: '/api/v{api-version}/formData', + ...options, + headers: { + 'Content-Type': null, + ...options?.headers + } +}); + +export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); + +export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); + +export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); + +export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); + +export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); + +export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); + +export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); + +export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); + +export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); + +export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); + +export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); + +export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); + +export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); + +export const uploadFile = (options: Options) => (options.client ?? client).post({ + ...urlSearchParamsBodySerializer, + url: '/api/v{api-version}/upload', + ...options, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + ...options.headers + } +}); + +export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); + +export const complexTypes = (options: Options) => (options.client ?? client).get({ + querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, + url: '/api/v{api-version}/complex', + ...options +}); + +export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); + +export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ + ...formDataBodySerializer, + url: '/api/v{api-version}/multipart', + ...options, + headers: { + 'Content-Type': null, + ...options?.headers + } +}); + +export const complexParams = (options: Options) => (options.client ?? client).put({ + url: '/api/v{api-version}/complex/{id}', + ...options, + headers: { + 'Content-Type': 'application/json-patch+json', + ...options.headers + } +}); + +export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); + +export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); + +export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); + +/** + * Login User + */ +export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ + ...urlSearchParamsBodySerializer, + url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', + ...options, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + ...options.headers + } +}); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/types.gen.ts new file mode 100644 index 0000000000..3287ee8737 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery-disabled/types.gen.ts @@ -0,0 +1,2081 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type ClientOptions = { + baseUrl: 'http://localhost:3000/base' | (string & {}); +}; + +/** + * Model with number-only name + */ +export type _400 = string; + +export type ExternalRefA = ExternalSharedModel; + +export type ExternalRefB = ExternalSharedModel; + +/** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ +export type CamelCaseCommentWithBreaks = number; + +/** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ +export type CommentWithBreaks = number; + +/** + * Testing backticks in string: `backticks` and ```multiple backticks``` should work + */ +export type CommentWithBackticks = number; + +/** + * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work + */ +export type CommentWithBackticksAndQuotes = number; + +/** + * Testing slashes in string: \backwards\\\ and /forwards/// should work + */ +export type CommentWithSlashes = number; + +/** + * Testing expression placeholders in string: ${expression} should work + */ +export type CommentWithExpressionPlaceholders = number; + +/** + * Testing quotes in string: 'single quote''' and "double quotes""" should work + */ +export type CommentWithQuotes = number; + +/** + * Testing reserved characters in string: * inline * and ** inline ** should work + */ +export type CommentWithReservedCharacters = number; + +/** + * This is a simple number + */ +export type SimpleInteger = number; + +/** + * This is a simple boolean + */ +export type SimpleBoolean = boolean; + +/** + * This is a simple string + */ +export type SimpleString = string; + +/** + * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) + */ +export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; + +/** + * This is a simple file + */ +export type SimpleFile = Blob | File; + +/** + * This is a simple reference + */ +export type SimpleReference = ModelWithString; + +/** + * This is a simple string + */ +export type SimpleStringWithPattern = string | null; + +/** + * This is a simple enum with strings + */ +export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; + +export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; + +/** + * This is a simple enum with numbers + */ +export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; + +/** + * Success=1,Warning=2,Error=3 + */ +export type EnumFromDescription = number; + +/** + * This is a simple enum with numbers + */ +export type EnumWithExtensions = 200 | 400 | 500; + +export type EnumWithXEnumNames = 0 | 1 | 2; + +/** + * This is a simple array with numbers + */ +export type ArrayWithNumbers = Array; + +/** + * This is a simple array with booleans + */ +export type ArrayWithBooleans = Array; + +/** + * This is a simple array with strings + */ +export type ArrayWithStrings = Array; + +/** + * This is a simple array with references + */ +export type ArrayWithReferences = Array; + +/** + * This is a simple array containing an array + */ +export type ArrayWithArray = Array>; + +/** + * This is a simple array with properties + */ +export type ArrayWithProperties = Array<{ + '16x16'?: CamelCaseCommentWithBreaks; + bar?: string; +}>; + +/** + * This is a simple array with any of properties + */ +export type ArrayWithAnyOfProperties = Array<{ + foo?: string; +} | { + bar?: string; +}>; + +export type AnyOfAnyAndNull = { + data?: unknown; +}; + +/** + * This is a simple array with any of properties + */ +export type AnyOfArrays = { + results?: Array<{ + foo?: string; + } | { + bar?: string; + }>; +}; + +/** + * This is a string dictionary + */ +export type DictionaryWithString = { + [key: string]: string; +}; + +export type DictionaryWithPropertiesAndAdditionalProperties = { + foo?: number; + bar?: boolean; + [key: string]: string | number | boolean | undefined; +}; + +/** + * This is a string reference + */ +export type DictionaryWithReference = { + [key: string]: ModelWithString; +}; + +/** + * This is a complex dictionary + */ +export type DictionaryWithArray = { + [key: string]: Array; +}; + +/** + * This is a string dictionary + */ +export type DictionaryWithDictionary = { + [key: string]: { + [key: string]: string; + }; +}; + +/** + * This is a complex dictionary + */ +export type DictionaryWithProperties = { + [key: string]: { + foo?: string; + bar?: string; + }; +}; + +/** + * This is a model with one number property + */ +export type ModelWithInteger = { + /** + * This is a simple number property + */ + prop?: number; +}; + +/** + * This is a model with one boolean property + */ +export type ModelWithBoolean = { + /** + * This is a simple boolean property + */ + prop?: boolean; +}; + +/** + * This is a model with one string property + */ +export type ModelWithString = { + /** + * This is a simple string property + */ + prop?: string; +}; + +/** + * This is a model with one string property + */ +export type ModelWithStringError = { + /** + * This is a simple string property + */ + prop?: string; +}; + +/** + * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) + */ +export type ModelFromZendesk = string; + +/** + * This is a model with one string property + */ +export type ModelWithNullableString = { + /** + * This is a simple string property + */ + nullableProp1?: string | null; + /** + * This is a simple string property + */ + nullableRequiredProp1: string | null; + /** + * This is a simple string property + */ + nullableProp2?: string | null; + /** + * This is a simple string property + */ + nullableRequiredProp2: string | null; + /** + * This is a simple enum with strings + */ + 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; +}; + +/** + * This is a model with one enum + */ +export type ModelWithEnum = { + /** + * This is a simple enum with strings + */ + 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; + /** + * These are the HTTP error code enums + */ + statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; + /** + * Simple boolean enum + */ + bool?: true; +}; + +/** + * This is a model with one enum with escaped name + */ +export type ModelWithEnumWithHyphen = { + /** + * Foo-Bar-Baz-Qux + */ + 'foo-bar-baz-qux'?: '3.0'; +}; + +/** + * This is a model with one enum + */ +export type ModelWithEnumFromDescription = { + /** + * Success=1,Warning=2,Error=3 + */ + test?: number; +}; + +/** + * This is a model with nested enums + */ +export type ModelWithNestedEnums = { + dictionaryWithEnum?: { + [key: string]: 'Success' | 'Warning' | 'Error'; + }; + dictionaryWithEnumFromDescription?: { + [key: string]: number; + }; + arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; + arrayWithDescription?: Array; + /** + * This is a simple enum with strings + */ + 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; +}; + +/** + * This is a model with one property containing a reference + */ +export type ModelWithReference = { + prop?: ModelWithProperties; +}; + +/** + * This is a model with one property containing an array + */ +export type ModelWithArrayReadOnlyAndWriteOnly = { + prop?: Array; + propWithFile?: Array; + propWithNumber?: Array; +}; + +/** + * This is a model with one property containing an array + */ +export type ModelWithArray = { + prop?: Array; + propWithFile?: Array; + propWithNumber?: Array; +}; + +/** + * This is a model with one property containing a dictionary + */ +export type ModelWithDictionary = { + prop?: { + [key: string]: string; + }; +}; + +/** + * This is a deprecated model with a deprecated property + * + * @deprecated + */ +export type DeprecatedModel = { + /** + * This is a deprecated property + * + * @deprecated + */ + prop?: string; +}; + +/** + * This is a model with one property containing a circular reference + */ +export type ModelWithCircularReference = { + prop?: ModelWithCircularReference; +}; + +/** + * This is a model with one property with a 'one of' relationship + */ +export type CompositionWithOneOf = { + propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; +}; + +/** + * This is a model with one property with a 'one of' relationship where the options are not $ref + */ +export type CompositionWithOneOfAnonymous = { + propA?: { + propA?: string; + } | string | number; +}; + +/** + * Circle + */ +export type ModelCircle = { + kind: string; + radius?: number; +}; + +/** + * Square + */ +export type ModelSquare = { + kind: string; + sideLength?: number; +}; + +/** + * This is a model with one property with a 'one of' relationship where the options are not $ref + */ +export type CompositionWithOneOfDiscriminator = ({ + kind: 'circle'; +} & ModelCircle) | ({ + kind: 'square'; +} & ModelSquare); + +/** + * This is a model with one property with a 'any of' relationship + */ +export type CompositionWithAnyOf = { + propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; +}; + +/** + * This is a model with one property with a 'any of' relationship where the options are not $ref + */ +export type CompositionWithAnyOfAnonymous = { + propA?: { + propA?: string; + } | string | number; +}; + +/** + * This is a model with nested 'any of' property with a type null + */ +export type CompositionWithNestedAnyAndTypeNull = { + propA?: Array | Array; +}; + +export type _3eNum1Период = 'Bird' | 'Dog'; + +export type ConstValue = 'ConstValue'; + +/** + * This is a model with one property with a 'any of' relationship where the options are not $ref + */ +export type CompositionWithNestedAnyOfAndNull = { + propA?: Array<_3eNum1Период | ConstValue> | null; +}; + +/** + * This is a model with one property with a 'one of' relationship + */ +export type CompositionWithOneOfAndNullable = { + propA?: { + boolean?: boolean; + } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; +}; + +/** + * This is a model that contains a simple dictionary within composition + */ +export type CompositionWithOneOfAndSimpleDictionary = { + propA?: boolean | { + [key: string]: number; + }; +}; + +/** + * This is a model that contains a dictionary of simple arrays within composition + */ +export type CompositionWithOneOfAndSimpleArrayDictionary = { + propA?: boolean | { + [key: string]: Array; + }; +}; + +/** + * This is a model that contains a dictionary of complex arrays (composited) within composition + */ +export type CompositionWithOneOfAndComplexArrayDictionary = { + propA?: boolean | { + [key: string]: Array; + }; +}; + +/** + * This is a model with one property with a 'all of' relationship + */ +export type CompositionWithAllOfAndNullable = { + propA?: ({ + boolean?: boolean; + } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; +}; + +/** + * This is a model with one property with a 'any of' relationship + */ +export type CompositionWithAnyOfAndNullable = { + propA?: { + boolean?: boolean; + } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; +}; + +/** + * This is a base model with two simple optional properties + */ +export type CompositionBaseModel = { + firstName?: string; + lastname?: string; +}; + +/** + * This is a model that extends the base model + */ +export type CompositionExtendedModel = CompositionBaseModel & { + age: number; + firstName: string; + lastname: string; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithProperties = { + required: string; + readonly requiredAndReadOnly: string; + requiredAndNullable: string | null; + string?: string; + number?: number; + boolean?: boolean; + reference?: ModelWithString; + 'property with space'?: string; + default?: string; + try?: string; + readonly '@namespace.string'?: string; + readonly '@namespace.integer'?: number; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithNestedProperties = { + readonly first: { + readonly second: { + readonly third: string | null; + } | null; + } | null; +}; + +/** + * This is a model with duplicated properties + */ +export type ModelWithDuplicateProperties = { + prop?: ModelWithString; +}; + +/** + * This is a model with ordered properties + */ +export type ModelWithOrderedProperties = { + zebra?: string; + apple?: string; + hawaii?: string; +}; + +/** + * This is a model with duplicated imports + */ +export type ModelWithDuplicateImports = { + propA?: ModelWithString; + propB?: ModelWithString; + propC?: ModelWithString; +}; + +/** + * This is a model that extends another model + */ +export type ModelThatExtends = ModelWithString & { + propExtendsA?: string; + propExtendsB?: ModelWithString; +}; + +/** + * This is a model that extends another model + */ +export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { + propExtendsC?: string; + propExtendsD?: ModelWithString; +}; + +/** + * This is a model that contains a some patterns + */ +export type ModelWithPattern = { + key: string; + name: string; + readonly enabled?: boolean; + readonly modified?: string; + id?: string; + text?: string; + patternWithSingleQuotes?: string; + patternWithNewline?: string; + patternWithBacktick?: string; + patternWithUnicode?: string; +}; + +export type File = { + /** + * Id + */ + readonly id?: string; + /** + * Updated at + */ + readonly updated_at?: string; + /** + * Created at + */ + readonly created_at?: string; + /** + * Mime + */ + mime: string; + /** + * File + */ + readonly file?: string; +}; + +export type Default = { + name?: string; +}; + +export type Pageable = { + page?: number; + size?: number; + sort?: Array; +}; + +/** + * This is a free-form object without additionalProperties. + */ +export type FreeFormObjectWithoutAdditionalProperties = { + [key: string]: unknown; +}; + +/** + * This is a free-form object with additionalProperties: true. + */ +export type FreeFormObjectWithAdditionalPropertiesEqTrue = { + [key: string]: unknown; +}; + +/** + * This is a free-form object with additionalProperties: {}. + */ +export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { + [key: string]: unknown; +}; + +export type ModelWithConst = { + String?: 'String'; + number?: 0; + null?: unknown; + withType?: 'Some string'; +}; + +/** + * This is a model with one property and additionalProperties: true + */ +export type ModelWithAdditionalPropertiesEqTrue = { + /** + * This is a simple string property + */ + prop?: string; + [key: string]: unknown; +}; + +export type NestedAnyOfArraysNullable = { + nullableArray?: Array | null; +}; + +export type CompositionWithOneOfAndProperties = ({ + foo: SimpleParameter; +} | { + bar: NonAsciiStringæøåÆøÅöôêÊ字符串; +}) & { + baz: number | null; + qux: number; +}; + +/** + * An object that can be null + */ +export type NullableObject = { + foo?: string; +} | null; + +/** + * Some % character + */ +export type CharactersInDescription = string; + +export type ModelWithNullableObject = { + data?: NullableObject; +}; + +/** + * An object with additional properties that can be null + */ +export type ModelWithAdditionalPropertiesRef = { + [key: string]: NullableObject | null; +}; + +export type ModelWithOneOfEnum = { + foo: 'Bar'; +} | { + foo: 'Baz'; +} | { + foo: 'Qux'; +} | { + content: string; + foo: 'Quux'; +} | { + content: [ + string, + string + ]; + foo: 'Corge'; +}; + +export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; + +export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; + +export type ModelWithNestedArrayEnumsData = { + foo?: Array; + bar?: Array; +}; + +export type ModelWithNestedArrayEnums = { + array_strings?: Array; + data?: ModelWithNestedArrayEnumsData; +}; + +export type ModelWithNestedCompositionEnums = { + foo?: ModelWithNestedArrayEnumsDataFoo; +}; + +export type ModelWithReadOnlyAndWriteOnly = { + foo: string; + readonly bar: string; +}; + +export type ModelWithConstantSizeArray = [ + number, + number +]; + +export type ModelWithAnyOfConstantSizeArray = [ + number | string, + number | string, + number | string +]; + +export type ModelWithPrefixItemsConstantSizeArray = Array; + +export type ModelWithAnyOfConstantSizeArrayNullable = [ + number | null | string, + number | null | string, + number | null | string +]; + +export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ + number | Import, + number | Import +]; + +export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ + number & string, + number & string +]; + +export type ModelWithNumericEnumUnion = { + /** + * Период + */ + value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; +}; + +/** + * Some description with `back ticks` + */ +export type ModelWithBackticksInDescription = { + /** + * The template `that` should be used for parsing and importing the contents of the CSV file. + * + *

There is one placeholder currently supported:

  • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

Example of a correct JSON template:

+ *
+     * [
+     * {
+     * "resourceType": "Asset",
+     * "identifier": {
+     * "name": "${1}",
+     * "domain": {
+     * "name": "${2}",
+     * "community": {
+     * "name": "Some Community"
+     * }
+     * }
+     * },
+     * "attributes" : {
+     * "00000000-0000-0000-0000-000000003115" : [ {
+     * "value" : "${3}"
+     * } ],
+     * "00000000-0000-0000-0000-000000000222" : [ {
+     * "value" : "${4}"
+     * } ]
+     * }
+     * }
+     * ]
+     * 
+ */ + template?: string; +}; + +export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { + baz: number | null; + qux: number; +}; + +/** + * Model used to test deduplication strategy (unused) + */ +export type ParameterSimpleParameterUnused = string; + +/** + * Model used to test deduplication strategy + */ +export type PostServiceWithEmptyTagResponse = string; + +/** + * Model used to test deduplication strategy + */ +export type PostServiceWithEmptyTagResponse2 = string; + +/** + * Model used to test deduplication strategy + */ +export type DeleteFooData = string; + +/** + * Model used to test deduplication strategy + */ +export type DeleteFooData2 = string; + +/** + * Model with restricted keyword name + */ +export type Import = string; + +export type SchemaWithFormRestrictedKeys = { + description?: string; + 'x-enum-descriptions'?: string; + 'x-enum-varnames'?: string; + 'x-enumNames'?: string; + title?: string; + object?: { + description?: string; + 'x-enum-descriptions'?: string; + 'x-enum-varnames'?: string; + 'x-enumNames'?: string; + title?: string; + }; + array?: Array<{ + description?: string; + 'x-enum-descriptions'?: string; + 'x-enum-varnames'?: string; + 'x-enumNames'?: string; + title?: string; + }>; +}; + +/** + * This schema was giving PascalCase transformations a hard time + */ +export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { + /** + * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. + */ + preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; +}; + +/** + * This schema was giving PascalCase transformations a hard time + */ +export type IoK8sApimachineryPkgApisMetaV1Preconditions = { + /** + * Specifies the target ResourceVersion + */ + resourceVersion?: string; + /** + * Specifies the target UID. + */ + uid?: string; +}; + +export type AdditionalPropertiesUnknownIssue = { + [key: string]: string | number; +}; + +export type AdditionalPropertiesUnknownIssue2 = { + [key: string]: string | number; +}; + +export type AdditionalPropertiesUnknownIssue3 = string & { + entries: { + [key: string]: AdditionalPropertiesUnknownIssue; + }; +}; + +export type AdditionalPropertiesIntegerIssue = { + value: number; + [key: string]: number; +}; + +export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; + +export type GenericSchemaDuplicateIssue1SystemBoolean = { + item?: boolean; + error?: string | null; + readonly hasError?: boolean; + data?: { + [key: string]: never; + }; +}; + +export type GenericSchemaDuplicateIssue1SystemString = { + item?: string | null; + error?: string | null; + readonly hasError?: boolean; +}; + +export type ExternalSharedModel = { + id: string; + name?: string; +}; + +/** + * This is a model with one property containing a reference + */ +export type ModelWithReferenceWritable = { + prop?: ModelWithPropertiesWritable; +}; + +/** + * This is a model with one property containing an array + */ +export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { + prop?: Array; + propWithFile?: Array; + propWithNumber?: Array; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithPropertiesWritable = { + required: string; + requiredAndNullable: string | null; + string?: string; + number?: number; + boolean?: boolean; + reference?: ModelWithString; + 'property with space'?: string; + default?: string; + try?: string; +}; + +/** + * This is a model that contains a some patterns + */ +export type ModelWithPatternWritable = { + key: string; + name: string; + id?: string; + text?: string; + patternWithSingleQuotes?: string; + patternWithNewline?: string; + patternWithBacktick?: string; + patternWithUnicode?: string; +}; + +export type FileWritable = { + /** + * Mime + */ + mime: string; +}; + +export type ModelWithReadOnlyAndWriteOnlyWritable = { + foo: string; + baz: string; +}; + +export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ + number | Import, + number | Import +]; + +export type AdditionalPropertiesUnknownIssueWritable = { + [key: string]: string | number; +}; + +export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; + +export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { + item?: boolean; + error?: string | null; + data?: { + [key: string]: never; + }; +}; + +export type GenericSchemaDuplicateIssue1SystemStringWritable = { + item?: string | null; + error?: string | null; +}; + +/** + * This is a reusable parameter + */ +export type SimpleParameter = string; + +/** + * Parameter with illegal characters + */ +export type XFooBar = ModelWithString; + +export type SimpleRequestBody = ModelWithString; + +export type SimpleFormData = ModelWithString; + +export type ExportData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type PatchApiVbyApiVersionNoTagData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type PatchApiVbyApiVersionNoTagResponses = { + /** + * OK + */ + default: unknown; +}; + +export type ImportData = { + body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type ImportResponses = { + /** + * Success + */ + 200: ModelFromZendesk; + /** + * Default success response + */ + default: ModelWithReadOnlyAndWriteOnly; +}; + +export type ImportResponse = ImportResponses[keyof ImportResponses]; + +export type FooWowData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type FooWowResponses = { + /** + * OK + */ + default: unknown; +}; + +export type ApiVVersionODataControllerCountData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple/$count'; +}; + +export type ApiVVersionODataControllerCountResponses = { + /** + * Success + */ + 200: ModelFromZendesk; +}; + +export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; + +export type GetApiVbyApiVersionSimpleOperationData = { + body?: never; + path: { + /** + * foo in method + */ + foo_param: string; + }; + query?: never; + url: '/api/v{api-version}/simple:operation'; +}; + +export type GetApiVbyApiVersionSimpleOperationErrors = { + /** + * Default error response + */ + default: ModelWithBoolean; +}; + +export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; + +export type GetApiVbyApiVersionSimpleOperationResponses = { + /** + * Response is a simple number + */ + 200: number; +}; + +export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; + +export type DeleteCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type GetCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type HeadCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type OptionsCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PatchCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PostCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PutCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type DeleteFooData3 = { + body?: never; + headers: { + /** + * Parameter with illegal characters + */ + 'x-Foo-Bar': ModelWithString; + }; + path: { + /** + * foo in method + */ + foo_param: string; + /** + * bar in method + */ + BarParam: string; + }; + query?: never; + url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; +}; + +export type CallWithDescriptionsData = { + body?: never; + path?: never; + query?: { + /** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ + parameterWithBreaks?: string; + /** + * Testing backticks in string: `backticks` and ```multiple backticks``` should work + */ + parameterWithBackticks?: string; + /** + * Testing slashes in string: \backwards\\\ and /forwards/// should work + */ + parameterWithSlashes?: string; + /** + * Testing expression placeholders in string: ${expression} should work + */ + parameterWithExpressionPlaceholders?: string; + /** + * Testing quotes in string: 'single quote''' and "double quotes""" should work + */ + parameterWithQuotes?: string; + /** + * Testing reserved characters in string: * inline * and ** inline ** should work + */ + parameterWithReservedCharacters?: string; + }; + url: '/api/v{api-version}/descriptions'; +}; + +export type DeprecatedCallData = { + body?: never; + headers: { + /** + * This parameter is deprecated + * + * @deprecated + */ + parameter: DeprecatedModel | null; + }; + path?: never; + query?: never; + url: '/api/v{api-version}/parameters/deprecated'; +}; + +export type CallWithParametersData = { + /** + * This is the parameter that goes into the body + */ + body: { + [key: string]: unknown; + } | null; + headers: { + /** + * This is the parameter that goes into the header + */ + parameterHeader: string | null; + }; + path: { + /** + * This is the parameter that goes into the path + */ + parameterPath: string | null; + /** + * api-version should be required in standalone clients + */ + 'api-version': string | null; + }; + query: { + foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; + foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; + /** + * This is the parameter that goes into the query params + */ + cursor: string | null; + }; + url: '/api/v{api-version}/parameters/{parameterPath}'; +}; + +export type CallWithWeirdParameterNamesData = { + /** + * This is the parameter that goes into the body + */ + body: ModelWithString | null; + headers: { + /** + * This is the parameter that goes into the request header + */ + 'parameter.header': string | null; + }; + path: { + /** + * This is the parameter that goes into the path + */ + 'parameter.path.1'?: string; + /** + * This is the parameter that goes into the path + */ + 'parameter-path-2'?: string; + /** + * This is the parameter that goes into the path + */ + 'PARAMETER-PATH-3'?: string; + /** + * api-version should be required in standalone clients + */ + 'api-version': string | null; + }; + query: { + /** + * This is the parameter with a reserved keyword + */ + default?: string; + /** + * This is the parameter that goes into the request query params + */ + 'parameter-query': string | null; + }; + url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; +}; + +export type GetCallWithOptionalParamData = { + /** + * This is a required parameter + */ + body: ModelWithOneOfEnum; + path?: never; + query?: { + /** + * This is an optional parameter + */ + page?: number; + }; + url: '/api/v{api-version}/parameters'; +}; + +export type PostCallWithOptionalParamData = { + /** + * This is an optional parameter + */ + body?: { + offset?: number | null; + }; + path?: never; + query: { + /** + * This is a required parameter + */ + parameter: Pageable; + }; + url: '/api/v{api-version}/parameters'; +}; + +export type PostCallWithOptionalParamResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Success + */ + 204: void; +}; + +export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; + +export type PostApiVbyApiVersionRequestBodyData = { + /** + * A reusable request body + */ + body?: SimpleRequestBody; + path?: never; + query?: { + /** + * This is a reusable parameter + */ + parameter?: string; + }; + url: '/api/v{api-version}/requestBody'; +}; + +export type PostApiVbyApiVersionFormDataData = { + /** + * A reusable request body + */ + body?: SimpleFormData; + path?: never; + query?: { + /** + * This is a reusable parameter + */ + parameter?: string; + }; + url: '/api/v{api-version}/formData'; +}; + +export type CallWithDefaultParametersData = { + body?: never; + path?: never; + query?: { + /** + * This is a simple string with default value + */ + parameterString?: string | null; + /** + * This is a simple number with default value + */ + parameterNumber?: number | null; + /** + * This is a simple boolean with default value + */ + parameterBoolean?: boolean | null; + /** + * This is a simple enum with default value + */ + parameterEnum?: 'Success' | 'Warning' | 'Error'; + /** + * This is a simple model with default value + */ + parameterModel?: ModelWithString | null; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type CallWithDefaultOptionalParametersData = { + body?: never; + path?: never; + query?: { + /** + * This is a simple string that is optional with default value + */ + parameterString?: string; + /** + * This is a simple number that is optional with default value + */ + parameterNumber?: number; + /** + * This is a simple boolean that is optional with default value + */ + parameterBoolean?: boolean; + /** + * This is a simple enum that is optional with default value + */ + parameterEnum?: 'Success' | 'Warning' | 'Error'; + /** + * This is a simple model that is optional with default value + */ + parameterModel?: ModelWithString; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type CallToTestOrderOfParamsData = { + body?: never; + path?: never; + query: { + /** + * This is a optional string with default + */ + parameterOptionalStringWithDefault?: string; + /** + * This is a optional string with empty default + */ + parameterOptionalStringWithEmptyDefault?: string; + /** + * This is a optional string with no default + */ + parameterOptionalStringWithNoDefault?: string; + /** + * This is a string with default + */ + parameterStringWithDefault: string; + /** + * This is a string with empty default + */ + parameterStringWithEmptyDefault: string; + /** + * This is a string with no default + */ + parameterStringWithNoDefault: string; + /** + * This is a string that can be null with no default + */ + parameterStringNullableWithNoDefault?: string | null; + /** + * This is a string that can be null with default + */ + parameterStringNullableWithDefault?: string | null; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type DuplicateNameData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName2Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName3Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName4Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type CallWithNoContentResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no-content'; +}; + +export type CallWithNoContentResponseResponses = { + /** + * Success + */ + 204: void; +}; + +export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; + +export type CallWithResponseAndNoContentResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/response-and-no-content'; +}; + +export type CallWithResponseAndNoContentResponseResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Success + */ + 204: void; +}; + +export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; + +export type DummyAData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/a'; +}; + +export type DummyAResponses = { + 200: _400; +}; + +export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; + +export type DummyBData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/b'; +}; + +export type DummyBResponses = { + /** + * Success + */ + 204: void; +}; + +export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; + +export type CallWithResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithResponseResponses = { + default: Import; +}; + +export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; + +export type CallWithDuplicateResponsesData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithDuplicateResponsesErrors = { + /** + * Message for 500 error + */ + 500: ModelWithStringError; + /** + * Message for 501 error + */ + 501: ModelWithStringError; + /** + * Message for 502 error + */ + 502: ModelWithStringError; + /** + * Message for 4XX errors + */ + '4XX': DictionaryWithArray; + /** + * Default error response + */ + default: ModelWithBoolean; +}; + +export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; + +export type CallWithDuplicateResponsesResponses = { + /** + * Message for 200 response + */ + 200: ModelWithBoolean & ModelWithInteger; + /** + * Message for 201 response + */ + 201: ModelWithString; + /** + * Message for 202 response + */ + 202: ModelWithString; +}; + +export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; + +export type CallWithResponsesData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithResponsesErrors = { + /** + * Message for 500 error + */ + 500: ModelWithStringError; + /** + * Message for 501 error + */ + 501: ModelWithStringError; + /** + * Message for 502 error + */ + 502: ModelWithStringError; + /** + * Message for default response + */ + default: ModelWithStringError; +}; + +export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; + +export type CallWithResponsesResponses = { + /** + * Message for 200 response + */ + 200: { + readonly '@namespace.string'?: string; + readonly '@namespace.integer'?: number; + readonly value?: Array; + }; + /** + * Message for 201 response + */ + 201: ModelThatExtends; + /** + * Message for 202 response + */ + 202: ModelThatExtendsExtends; +}; + +export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; + +export type CollectionFormatData = { + body?: never; + path?: never; + query: { + /** + * This is an array parameter that is sent as csv format (comma-separated values) + */ + parameterArrayCSV: Array | null; + /** + * This is an array parameter that is sent as ssv format (space-separated values) + */ + parameterArraySSV: Array | null; + /** + * This is an array parameter that is sent as tsv format (tab-separated values) + */ + parameterArrayTSV: Array | null; + /** + * This is an array parameter that is sent as pipes format (pipe-separated values) + */ + parameterArrayPipes: Array | null; + /** + * This is an array parameter that is sent as multi format (multiple parameter instances) + */ + parameterArrayMulti: Array | null; + }; + url: '/api/v{api-version}/collectionFormat'; +}; + +export type TypesData = { + body?: never; + path?: { + /** + * This is a number parameter + */ + id?: number; + }; + query: { + /** + * This is a number parameter + */ + parameterNumber: number; + /** + * This is a string parameter + */ + parameterString: string | null; + /** + * This is a boolean parameter + */ + parameterBoolean: boolean | null; + /** + * This is an object parameter + */ + parameterObject: { + [key: string]: unknown; + } | null; + /** + * This is an array parameter + */ + parameterArray: Array | null; + /** + * This is a dictionary parameter + */ + parameterDictionary: { + [key: string]: unknown; + } | null; + /** + * This is an enum parameter + */ + parameterEnum: 'Success' | 'Warning' | 'Error'; + }; + url: '/api/v{api-version}/types'; +}; + +export type TypesResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Response is a simple string + */ + 201: string; + /** + * Response is a simple boolean + */ + 202: boolean; + /** + * Response is a simple object + */ + 203: { + [key: string]: unknown; + }; +}; + +export type TypesResponse = TypesResponses[keyof TypesResponses]; + +export type UploadFileData = { + body: Blob | File; + path: { + /** + * api-version should be required in standalone clients + */ + 'api-version': string | null; + }; + query?: never; + url: '/api/v{api-version}/upload'; +}; + +export type UploadFileResponses = { + 200: boolean; +}; + +export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; + +export type FileResponseData = { + body?: never; + path: { + id: string; + /** + * api-version should be required in standalone clients + */ + 'api-version': string; + }; + query?: never; + url: '/api/v{api-version}/file/{id}'; +}; + +export type FileResponseResponses = { + /** + * Success + */ + 200: Blob | File; +}; + +export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; + +export type ComplexTypesData = { + body?: never; + path?: never; + query: { + /** + * Parameter containing object + */ + parameterObject: { + first?: { + second?: { + third?: string; + }; + }; + }; + /** + * Parameter containing reference + */ + parameterReference: ModelWithString; + }; + url: '/api/v{api-version}/complex'; +}; + +export type ComplexTypesErrors = { + /** + * 400 `server` error + */ + 400: unknown; + /** + * 500 server error + */ + 500: unknown; +}; + +export type ComplexTypesResponses = { + /** + * Successful response + */ + 200: Array; +}; + +export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; + +export type MultipartResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multipart'; +}; + +export type MultipartResponseResponses = { + /** + * OK + */ + 200: { + file?: Blob | File; + metadata?: { + foo?: string; + bar?: string; + }; + }; +}; + +export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; + +export type MultipartRequestData = { + body?: { + content?: Blob | File; + data?: ModelWithString | null; + }; + path?: never; + query?: never; + url: '/api/v{api-version}/multipart'; +}; + +export type ComplexParamsData = { + body?: { + readonly key: string | null; + name: string | null; + enabled?: boolean; + type: 'Monkey' | 'Horse' | 'Bird'; + listOfModels?: Array | null; + listOfStrings?: Array | null; + parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; + readonly user?: { + readonly id?: number; + readonly name?: string | null; + }; + }; + path: { + id: number; + /** + * api-version should be required in standalone clients + */ + 'api-version': string; + }; + query?: never; + url: '/api/v{api-version}/complex/{id}'; +}; + +export type ComplexParamsResponses = { + /** + * Success + */ + 200: ModelWithString; +}; + +export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; + +export type CallWithResultFromHeaderData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/header'; +}; + +export type CallWithResultFromHeaderErrors = { + /** + * 400 server error + */ + 400: unknown; + /** + * 500 server error + */ + 500: unknown; +}; + +export type CallWithResultFromHeaderResponses = { + /** + * Successful response + */ + 200: unknown; +}; + +export type TestErrorCodeData = { + body?: never; + path?: never; + query: { + /** + * Status code to return + */ + status: number; + }; + url: '/api/v{api-version}/error'; +}; + +export type TestErrorCodeErrors = { + /** + * Custom message: Internal Server Error + */ + 500: unknown; + /** + * Custom message: Not Implemented + */ + 501: unknown; + /** + * Custom message: Bad Gateway + */ + 502: unknown; + /** + * Custom message: Service Unavailable + */ + 503: unknown; +}; + +export type TestErrorCodeResponses = { + /** + * Custom message: Successful response + */ + 200: unknown; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Data = { + body?: never; + path?: never; + query: { + /** + * Dummy input param + */ + nonAsciiParamæøåÆØÅöôêÊ: number; + }; + url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { + /** + * Successful response + */ + 200: Array; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; + +export type PutWithFormUrlEncodedData = { + body: ArrayWithStrings; + path?: never; + query?: never; + url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/@tanstack/react-query.gen.ts new file mode 100644 index 0000000000..40c8901183 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/@tanstack/react-query.gen.ts @@ -0,0 +1,840 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/react-query'; + +import { client } from '../client.gen'; +import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; +import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; + +export type QueryKey = [ + Pick & { + _id: string; + _infinite?: boolean; + tags?: ReadonlyArray; + } +]; + +const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ + QueryKey[0] +] => { + const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; + if (infinite) { + params._infinite = infinite; + } + if (tags) { + params.tags = tags; + } + if (options?.body) { + params.body = options.body; + } + if (options?.headers) { + params.headers = options.headers; + } + if (options?.path) { + params.path = options.path; + } + if (options?.query) { + params.query = options.query; + } + return [params]; +}; + +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + +export const exportQueryKey = (options?: Options) => createQueryKey('export', options); + +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await export_({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: exportQueryKey(resolveOptions(options)) +}); + +const queryWithOptions = (optionsFn: Function, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useExportQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(exportOptions, options); + +export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await patchApiVbyApiVersionNoTag({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const importMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await import_({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const fooWowMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await fooWow({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); + +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await apiVVersionODataControllerCount({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: apiVVersionODataControllerCountQueryKey(resolveOptions(options)) +}); + +export const useApiVVersionODataControllerCountQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(apiVVersionODataControllerCountOptions, options); + +export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); + +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await getApiVbyApiVersionSimpleOperation({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: getApiVbyApiVersionSimpleOperationQueryKey(resolveOptions(options)) +}); + +export const useGetApiVbyApiVersionSimpleOperationQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getApiVbyApiVersionSimpleOperationOptions, options); + +export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deleteCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); + +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await getCallWithoutParametersAndResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: getCallWithoutParametersAndResponseQueryKey(resolveOptions(options)) +}); + +export const useGetCallWithoutParametersAndResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithoutParametersAndResponseOptions, options); + +export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await patchCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await putCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const deleteFooMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deleteFoo({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDescriptions({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * @deprecated + */ +export const deprecatedCallMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deprecatedCall({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithParametersMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithParameters({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithWeirdParameterNames({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); + +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await getCallWithOptionalParam({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: getCallWithOptionalParamQueryKey(resolveOptions(options)) +}); + +const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { + const params = { ...queryKey[0] }; + if (page.body) { + params.body = { + ...queryKey[0].body as any, + ...page.body as any + }; + } + if (page.headers) { + params.headers = { + ...queryKey[0].headers, + ...page.headers + }; + } + if (page.path) { + params.path = { + ...queryKey[0].path as any, + ...page.path as any + }; + } + if (page.query) { + params.query = { + ...queryKey[0].query as any, + ...page.query as any + }; + } + return params as unknown as typeof page; +}; + +export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); + +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +// @ts-ignore +{ + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { + // @ts-ignore + const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { + query: { + page: pageParam + } + }; + const params = createInfiniteParams(queryKey, page); + const { data } = await getCallWithOptionalParam({ + ...options, + ...params, + signal, + throwOnError: true + }); + return data; + }), + queryKey: getCallWithOptionalParamInfiniteQueryKey(resolveOptions(options)) +}); + +export const useGetCallWithOptionalParamQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithOptionalParamOptions, options); + +export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postCallWithOptionalParam({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postApiVbyApiVersionRequestBody({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postApiVbyApiVersionFormData({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); + +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithDefaultParameters({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithDefaultParametersQueryKey(resolveOptions(options)) +}); + +export const useCallWithDefaultParametersQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithDefaultParametersOptions, options); + +export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDefaultOptionalParameters({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callToTestOrderOfParams({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateNameMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); + +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await duplicateName2({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) +}); + +export const useDuplicateName2Query = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(duplicateName2Options, options); + +export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName3({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName4({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); + +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithNoContentResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithNoContentResponseQueryKey(resolveOptions(options)) +}); + +export const useCallWithNoContentResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithNoContentResponseOptions, options); + +export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); + +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithResponseAndNoContentResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithResponseAndNoContentResponseQueryKey(resolveOptions(options)) +}); + +export const useCallWithResponseAndNoContentResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseAndNoContentResponseOptions, options); + +export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); + +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await dummyA({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: dummyAQueryKey(resolveOptions(options)) +}); + +export const useDummyAQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyAOptions, options); + +export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); + +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await dummyB({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: dummyBQueryKey(resolveOptions(options)) +}); + +export const useDummyBQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyBOptions, options); + +export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); + +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) +}); + +export const useCallWithResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseOptions, options); + +export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDuplicateResponses({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithResponses({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); + +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await collectionFormat({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) +}); + +export const useCollectionFormatQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(collectionFormatOptions, options); + +export const typesQueryKey = (options: Options) => createQueryKey('types', options); + +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await types({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: typesQueryKey(resolveOptions(options)) +}); + +export const useTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(typesOptions, options); + +export const uploadFileMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await uploadFile({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); + +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await fileResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) +}); + +export const useFileResponseQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(fileResponseOptions, options); + +export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); + +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await complexTypes({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) +}); + +export const useComplexTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(complexTypesOptions, options); + +export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); + +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await multipartResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: multipartResponseQueryKey(resolveOptions(options)) +}); + +export const useMultipartResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(multipartResponseOptions, options); + +export const multipartRequestMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await multipartRequest({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const complexParamsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await complexParams({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithResultFromHeader({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await testErrorCode({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * Login User + */ +export const putWithFormUrlEncodedMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await putWithFormUrlEncoded({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/client.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/client.gen.ts new file mode 100644 index 0000000000..25cd14eafb --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/client.gen.ts @@ -0,0 +1,16 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type ClientOptions, type Config, createClient, createConfig } from './client'; +import type { ClientOptions as ClientOptions2 } from './types.gen'; + +/** + * The `createClientConfig()` function will be called on client initialization + * and the returned object will become the client's initial configuration. + * + * You may want to initialize your client this way instead of calling + * `setConfig()`. This is useful for example if you're using Next.js + * to ensure your client always has the correct values. + */ +export type CreateClientConfig = (override?: Config) => Config & T>; + +export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/client/client.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/client/client.gen.ts new file mode 100644 index 0000000000..14dc0a0ec5 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/client/client.gen.ts @@ -0,0 +1,290 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { createSseClient } from '../core/serverSentEvents.gen'; +import type { HttpMethod } from '../core/types.gen'; +import { getValidRequestBody } from '../core/utils.gen'; +import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; +import { + buildUrl, + createConfig, + createInterceptors, + getParseAs, + mergeConfigs, + mergeHeaders, + setAuthParams, +} from './utils.gen'; + +type ReqInit = Omit & { + body?: any; + headers: ReturnType; +}; + +export const createClient = (config: Config = {}): Client => { + let _config = mergeConfigs(createConfig(), config); + + const getConfig = (): Config => ({ ..._config }); + + const setConfig = (config: Config): Config => { + _config = mergeConfigs(_config, config); + return getConfig(); + }; + + const interceptors = createInterceptors(); + + const beforeRequest = async (options: RequestOptions) => { + const opts = { + ..._config, + ...options, + fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, + headers: mergeHeaders(_config.headers, options.headers), + serializedBody: undefined as string | undefined, + }; + + if (opts.security) { + await setAuthParams({ + ...opts, + security: opts.security, + }); + } + + if (opts.requestValidator) { + await opts.requestValidator(opts); + } + + if (opts.body !== undefined && opts.bodySerializer) { + opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; + } + + // remove Content-Type header if body is empty to avoid sending invalid requests + if (opts.body === undefined || opts.serializedBody === '') { + opts.headers.delete('Content-Type'); + } + + const url = buildUrl(opts); + + return { opts, url }; + }; + + const request: Client['request'] = async (options) => { + // @ts-expect-error + const { opts, url } = await beforeRequest(options); + const requestInit: ReqInit = { + redirect: 'follow', + ...opts, + body: getValidRequestBody(opts), + }; + + let request = new Request(url, requestInit); + + for (const fn of interceptors.request.fns) { + if (fn) { + request = await fn(request, opts); + } + } + + // fetch must be assigned here, otherwise it would throw the error: + // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation + const _fetch = opts.fetch!; + let response: Response; + + try { + response = await _fetch(request); + } catch (error) { + // Handle fetch exceptions (AbortError, network errors, etc.) + let finalError = error; + + for (const fn of interceptors.error.fns) { + if (fn) { + finalError = (await fn(error, undefined as any, request, opts)) as unknown; + } + } + + finalError = finalError || ({} as unknown); + + if (opts.throwOnError) { + throw finalError; + } + + // Return error response + return opts.responseStyle === 'data' + ? undefined + : { + error: finalError, + request, + response: undefined as any, + }; + } + + for (const fn of interceptors.response.fns) { + if (fn) { + response = await fn(response, request, opts); + } + } + + const result = { + request, + response, + }; + + if (response.ok) { + const parseAs = + (opts.parseAs === 'auto' + ? getParseAs(response.headers.get('Content-Type')) + : opts.parseAs) ?? 'json'; + + if (response.status === 204 || response.headers.get('Content-Length') === '0') { + let emptyData: any; + switch (parseAs) { + case 'arrayBuffer': + case 'blob': + case 'text': + emptyData = await response[parseAs](); + break; + case 'formData': + emptyData = new FormData(); + break; + case 'stream': + emptyData = response.body; + break; + case 'json': + default: + emptyData = {}; + break; + } + return opts.responseStyle === 'data' + ? emptyData + : { + data: emptyData, + ...result, + }; + } + + let data: any; + switch (parseAs) { + case 'arrayBuffer': + case 'blob': + case 'formData': + case 'text': + data = await response[parseAs](); + break; + case 'json': { + // Some servers return 200 with no Content-Length and empty body. + // response.json() would throw; read as text and parse if non-empty. + const text = await response.text(); + data = text ? JSON.parse(text) : {}; + break; + } + case 'stream': + return opts.responseStyle === 'data' + ? response.body + : { + data: response.body, + ...result, + }; + } + + if (parseAs === 'json') { + if (opts.responseValidator) { + await opts.responseValidator(data); + } + + if (opts.responseTransformer) { + data = await opts.responseTransformer(data); + } + } + + return opts.responseStyle === 'data' + ? data + : { + data, + ...result, + }; + } + + const textError = await response.text(); + let jsonError: unknown; + + try { + jsonError = JSON.parse(textError); + } catch { + // noop + } + + const error = jsonError ?? textError; + let finalError = error; + + for (const fn of interceptors.error.fns) { + if (fn) { + finalError = (await fn(error, response, request, opts)) as string; + } + } + + finalError = finalError || ({} as string); + + if (opts.throwOnError) { + throw finalError; + } + + // TODO: we probably want to return error and improve types + return opts.responseStyle === 'data' + ? undefined + : { + error: finalError, + ...result, + }; + }; + + const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => + request({ ...options, method }); + + const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { + const { opts, url } = await beforeRequest(options); + return createSseClient({ + ...opts, + body: opts.body as BodyInit | null | undefined, + headers: opts.headers as unknown as Record, + method, + onRequest: async (url, init) => { + let request = new Request(url, init); + for (const fn of interceptors.request.fns) { + if (fn) { + request = await fn(request, opts); + } + } + return request; + }, + serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, + url, + }); + }; + + const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); + + return { + buildUrl: _buildUrl, + connect: makeMethodFn('CONNECT'), + delete: makeMethodFn('DELETE'), + get: makeMethodFn('GET'), + getConfig, + head: makeMethodFn('HEAD'), + interceptors, + options: makeMethodFn('OPTIONS'), + patch: makeMethodFn('PATCH'), + post: makeMethodFn('POST'), + put: makeMethodFn('PUT'), + request, + setConfig, + sse: { + connect: makeSseFn('CONNECT'), + delete: makeSseFn('DELETE'), + get: makeSseFn('GET'), + head: makeSseFn('HEAD'), + options: makeSseFn('OPTIONS'), + patch: makeSseFn('PATCH'), + post: makeSseFn('POST'), + put: makeSseFn('PUT'), + trace: makeSseFn('TRACE'), + }, + trace: makeMethodFn('TRACE'), + } as Client; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/client/index.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/client/index.ts new file mode 100644 index 0000000000..b295edeca0 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/client/index.ts @@ -0,0 +1,25 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type { Auth } from '../core/auth.gen'; +export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; +export { + formDataBodySerializer, + jsonBodySerializer, + urlSearchParamsBodySerializer, +} from '../core/bodySerializer.gen'; +export { buildClientParams } from '../core/params.gen'; +export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; +export { createClient } from './client.gen'; +export type { + Client, + ClientOptions, + Config, + CreateClientConfig, + Options, + RequestOptions, + RequestResult, + ResolvedRequestOptions, + ResponseStyle, + TDataShape, +} from './types.gen'; +export { createConfig, mergeHeaders } from './utils.gen'; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/client/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/client/types.gen.ts new file mode 100644 index 0000000000..a3f8616511 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/client/types.gen.ts @@ -0,0 +1,214 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Auth } from '../core/auth.gen'; +import type { + ServerSentEventsOptions, + ServerSentEventsResult, +} from '../core/serverSentEvents.gen'; +import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; +import type { Middleware } from './utils.gen'; + +export type ResponseStyle = 'data' | 'fields'; + +export interface Config + extends Omit, CoreConfig { + /** + * Base URL for all requests made by this client. + */ + baseUrl?: T['baseUrl']; + /** + * Fetch API implementation. You can use this option to provide a custom + * fetch instance. + * + * @default globalThis.fetch + */ + fetch?: typeof fetch; + /** + * Please don't use the Fetch client for Next.js applications. The `next` + * options won't have any effect. + * + * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. + */ + next?: never; + /** + * Return the response data parsed in a specified format. By default, `auto` + * will infer the appropriate method from the `Content-Type` response header. + * You can override this behavior with any of the {@link Body} methods. + * Select `stream` if you don't want to parse response data at all. + * + * @default 'auto' + */ + parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; + /** + * Should we return only data or multiple fields (data, error, response, etc.)? + * + * @default 'fields' + */ + responseStyle?: ResponseStyle; + /** + * Throw an error instead of returning it in the response? + * + * @default false + */ + throwOnError?: T['throwOnError']; +} + +export interface RequestOptions< + TData = unknown, + TResponseStyle extends ResponseStyle = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, +> + extends + Config<{ + responseStyle: TResponseStyle; + throwOnError: ThrowOnError; + }>, + Pick< + ServerSentEventsOptions, + | 'onRequest' + | 'onSseError' + | 'onSseEvent' + | 'sseDefaultRetryDelay' + | 'sseMaxRetryAttempts' + | 'sseMaxRetryDelay' + > { + /** + * Any body that you want to add to your request. + * + * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} + */ + body?: unknown; + path?: Record; + query?: Record; + /** + * Security mechanism(s) to use for the request. + */ + security?: ReadonlyArray; + url: Url; +} + +export interface ResolvedRequestOptions< + TResponseStyle extends ResponseStyle = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, +> extends RequestOptions { + serializedBody?: string; +} + +export type RequestResult< + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = boolean, + TResponseStyle extends ResponseStyle = 'fields', +> = ThrowOnError extends true + ? Promise< + TResponseStyle extends 'data' + ? TData extends Record + ? TData[keyof TData] + : TData + : { + data: TData extends Record ? TData[keyof TData] : TData; + request: Request; + response: Response; + } + > + : Promise< + TResponseStyle extends 'data' + ? (TData extends Record ? TData[keyof TData] : TData) | undefined + : ( + | { + data: TData extends Record ? TData[keyof TData] : TData; + error: undefined; + } + | { + data: undefined; + error: TError extends Record ? TError[keyof TError] : TError; + } + ) & { + request: Request; + response: Response; + } + >; + +export interface ClientOptions { + baseUrl?: string; + responseStyle?: ResponseStyle; + throwOnError?: boolean; +} + +type MethodFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'>, +) => RequestResult; + +type SseFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'>, +) => Promise>; + +type RequestFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'> & + Pick>, 'method'>, +) => RequestResult; + +type BuildUrlFn = < + TData extends { + body?: unknown; + path?: Record; + query?: Record; + url: string; + }, +>( + options: TData & Options, +) => string; + +export type Client = CoreClient & { + interceptors: Middleware; +}; + +/** + * The `createClientConfig()` function will be called on client initialization + * and the returned object will become the client's initial configuration. + * + * You may want to initialize your client this way instead of calling + * `setConfig()`. This is useful for example if you're using Next.js + * to ensure your client always has the correct values. + */ +export type CreateClientConfig = ( + override?: Config, +) => Config & T>; + +export interface TDataShape { + body?: unknown; + headers?: unknown; + path?: unknown; + query?: unknown; + url: string; +} + +type OmitKeys = Pick>; + +export type Options< + TData extends TDataShape = TDataShape, + ThrowOnError extends boolean = boolean, + TResponse = unknown, + TResponseStyle extends ResponseStyle = 'fields', +> = OmitKeys< + RequestOptions, + 'body' | 'path' | 'query' | 'url' +> & + ([TData] extends [never] ? unknown : Omit); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/client/utils.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/client/utils.gen.ts new file mode 100644 index 0000000000..b4bd2435ce --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/client/utils.gen.ts @@ -0,0 +1,316 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { getAuthToken } from '../core/auth.gen'; +import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; +import { jsonBodySerializer } from '../core/bodySerializer.gen'; +import { + serializeArrayParam, + serializeObjectParam, + serializePrimitiveParam, +} from '../core/pathSerializer.gen'; +import { getUrl } from '../core/utils.gen'; +import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; + +export const createQuerySerializer = ({ + parameters = {}, + ...args +}: QuerySerializerOptions = {}) => { + const querySerializer = (queryParams: T) => { + const search: string[] = []; + if (queryParams && typeof queryParams === 'object') { + for (const name in queryParams) { + const value = queryParams[name]; + + if (value === undefined || value === null) { + continue; + } + + const options = parameters[name] || args; + + if (Array.isArray(value)) { + const serializedArray = serializeArrayParam({ + allowReserved: options.allowReserved, + explode: true, + name, + style: 'form', + value, + ...options.array, + }); + if (serializedArray) search.push(serializedArray); + } else if (typeof value === 'object') { + const serializedObject = serializeObjectParam({ + allowReserved: options.allowReserved, + explode: true, + name, + style: 'deepObject', + value: value as Record, + ...options.object, + }); + if (serializedObject) search.push(serializedObject); + } else { + const serializedPrimitive = serializePrimitiveParam({ + allowReserved: options.allowReserved, + name, + value: value as string, + }); + if (serializedPrimitive) search.push(serializedPrimitive); + } + } + } + return search.join('&'); + }; + return querySerializer; +}; + +/** + * Infers parseAs value from provided Content-Type header. + */ +export const getParseAs = (contentType: string | null): Exclude => { + if (!contentType) { + // If no Content-Type header is provided, the best we can do is return the raw response body, + // which is effectively the same as the 'stream' option. + return 'stream'; + } + + const cleanContent = contentType.split(';')[0]?.trim(); + + if (!cleanContent) { + return; + } + + if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { + return 'json'; + } + + if (cleanContent === 'multipart/form-data') { + return 'formData'; + } + + if ( + ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) + ) { + return 'blob'; + } + + if (cleanContent.startsWith('text/')) { + return 'text'; + } + + return; +}; + +const checkForExistence = ( + options: Pick & { + headers: Headers; + }, + name?: string, +): boolean => { + if (!name) { + return false; + } + if ( + options.headers.has(name) || + options.query?.[name] || + options.headers.get('Cookie')?.includes(`${name}=`) + ) { + return true; + } + return false; +}; + +export const setAuthParams = async ({ + security, + ...options +}: Pick, 'security'> & + Pick & { + headers: Headers; + }) => { + for (const auth of security) { + if (checkForExistence(options, auth.name)) { + continue; + } + + const token = await getAuthToken(auth, options.auth); + + if (!token) { + continue; + } + + const name = auth.name ?? 'Authorization'; + + switch (auth.in) { + case 'query': + if (!options.query) { + options.query = {}; + } + options.query[name] = token; + break; + case 'cookie': + options.headers.append('Cookie', `${name}=${token}`); + break; + case 'header': + default: + options.headers.set(name, token); + break; + } + } +}; + +export const buildUrl: Client['buildUrl'] = (options) => + getUrl({ + baseUrl: options.baseUrl as string, + path: options.path, + query: options.query, + querySerializer: + typeof options.querySerializer === 'function' + ? options.querySerializer + : createQuerySerializer(options.querySerializer), + url: options.url, + }); + +export const mergeConfigs = (a: Config, b: Config): Config => { + const config = { ...a, ...b }; + if (config.baseUrl?.endsWith('/')) { + config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); + } + config.headers = mergeHeaders(a.headers, b.headers); + return config; +}; + +const headersEntries = (headers: Headers): Array<[string, string]> => { + const entries: Array<[string, string]> = []; + headers.forEach((value, key) => { + entries.push([key, value]); + }); + return entries; +}; + +export const mergeHeaders = ( + ...headers: Array['headers'] | undefined> +): Headers => { + const mergedHeaders = new Headers(); + for (const header of headers) { + if (!header) { + continue; + } + + const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); + + for (const [key, value] of iterator) { + if (value === null) { + mergedHeaders.delete(key); + } else if (Array.isArray(value)) { + for (const v of value) { + mergedHeaders.append(key, v as string); + } + } else if (value !== undefined) { + // assume object headers are meant to be JSON stringified, i.e. their + // content value in OpenAPI specification is 'application/json' + mergedHeaders.set( + key, + typeof value === 'object' ? JSON.stringify(value) : (value as string), + ); + } + } + } + return mergedHeaders; +}; + +type ErrInterceptor = ( + error: Err, + response: Res, + request: Req, + options: Options, +) => Err | Promise; + +type ReqInterceptor = (request: Req, options: Options) => Req | Promise; + +type ResInterceptor = ( + response: Res, + request: Req, + options: Options, +) => Res | Promise; + +class Interceptors { + fns: Array = []; + + clear(): void { + this.fns = []; + } + + eject(id: number | Interceptor): void { + const index = this.getInterceptorIndex(id); + if (this.fns[index]) { + this.fns[index] = null; + } + } + + exists(id: number | Interceptor): boolean { + const index = this.getInterceptorIndex(id); + return Boolean(this.fns[index]); + } + + getInterceptorIndex(id: number | Interceptor): number { + if (typeof id === 'number') { + return this.fns[id] ? id : -1; + } + return this.fns.indexOf(id); + } + + update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { + const index = this.getInterceptorIndex(id); + if (this.fns[index]) { + this.fns[index] = fn; + return id; + } + return false; + } + + use(fn: Interceptor): number { + this.fns.push(fn); + return this.fns.length - 1; + } +} + +export interface Middleware { + error: Interceptors>; + request: Interceptors>; + response: Interceptors>; +} + +export const createInterceptors = (): Middleware< + Req, + Res, + Err, + Options +> => ({ + error: new Interceptors>(), + request: new Interceptors>(), + response: new Interceptors>(), +}); + +const defaultQuerySerializer = createQuerySerializer({ + allowReserved: false, + array: { + explode: true, + style: 'form', + }, + object: { + explode: true, + style: 'deepObject', + }, +}); + +const defaultHeaders = { + 'Content-Type': 'application/json', +}; + +export const createConfig = ( + override: Config & T> = {}, +): Config & T> => ({ + ...jsonBodySerializer, + headers: defaultHeaders, + parseAs: 'auto', + querySerializer: defaultQuerySerializer, + ...override, +}); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/auth.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/auth.gen.ts new file mode 100644 index 0000000000..3ebf994788 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/auth.gen.ts @@ -0,0 +1,41 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type AuthToken = string | undefined; + +export interface Auth { + /** + * Which part of the request do we use to send the auth? + * + * @default 'header' + */ + in?: 'header' | 'query' | 'cookie'; + /** + * Header or query parameter name. + * + * @default 'Authorization' + */ + name?: string; + scheme?: 'basic' | 'bearer'; + type: 'apiKey' | 'http'; +} + +export const getAuthToken = async ( + auth: Auth, + callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, +): Promise => { + const token = typeof callback === 'function' ? await callback(auth) : callback; + + if (!token) { + return; + } + + if (auth.scheme === 'bearer') { + return `Bearer ${token}`; + } + + if (auth.scheme === 'basic') { + return `Basic ${btoa(token)}`; + } + + return token; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/bodySerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/bodySerializer.gen.ts new file mode 100644 index 0000000000..67daca60f8 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/bodySerializer.gen.ts @@ -0,0 +1,82 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; + +export type QuerySerializer = (query: Record) => string; + +export type BodySerializer = (body: unknown) => unknown; + +type QuerySerializerOptionsObject = { + allowReserved?: boolean; + array?: Partial>; + object?: Partial>; +}; + +export type QuerySerializerOptions = QuerySerializerOptionsObject & { + /** + * Per-parameter serialization overrides. When provided, these settings + * override the global array/object settings for specific parameter names. + */ + parameters?: Record; +}; + +const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { + if (typeof value === 'string' || value instanceof Blob) { + data.append(key, value); + } else if (value instanceof Date) { + data.append(key, value.toISOString()); + } else { + data.append(key, JSON.stringify(value)); + } +}; + +const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { + if (typeof value === 'string') { + data.append(key, value); + } else { + data.append(key, JSON.stringify(value)); + } +}; + +export const formDataBodySerializer = { + bodySerializer: (body: unknown): FormData => { + const data = new FormData(); + + Object.entries(body as Record).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + if (Array.isArray(value)) { + value.forEach((v) => serializeFormDataPair(data, key, v)); + } else { + serializeFormDataPair(data, key, value); + } + }); + + return data; + }, +}; + +export const jsonBodySerializer = { + bodySerializer: (body: unknown): string => + JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), +}; + +export const urlSearchParamsBodySerializer = { + bodySerializer: (body: unknown): string => { + const data = new URLSearchParams(); + + Object.entries(body as Record).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + if (Array.isArray(value)) { + value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); + } else { + serializeUrlSearchParamsPair(data, key, value); + } + }); + + return data.toString(); + }, +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/params.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/params.gen.ts new file mode 100644 index 0000000000..7955601a5c --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/params.gen.ts @@ -0,0 +1,169 @@ +// This file is auto-generated by @hey-api/openapi-ts + +type Slot = 'body' | 'headers' | 'path' | 'query'; + +export type Field = + | { + in: Exclude; + /** + * Field name. This is the name we want the user to see and use. + */ + key: string; + /** + * Field mapped name. This is the name we want to use in the request. + * If omitted, we use the same value as `key`. + */ + map?: string; + } + | { + in: Extract; + /** + * Key isn't required for bodies. + */ + key?: string; + map?: string; + } + | { + /** + * Field name. This is the name we want the user to see and use. + */ + key: string; + /** + * Field mapped name. This is the name we want to use in the request. + * If `in` is omitted, `map` aliases `key` to the transport layer. + */ + map: Slot; + }; + +export interface Fields { + allowExtra?: Partial>; + args?: ReadonlyArray; +} + +export type FieldsConfig = ReadonlyArray; + +const extraPrefixesMap: Record = { + $body_: 'body', + $headers_: 'headers', + $path_: 'path', + $query_: 'query', +}; +const extraPrefixes = Object.entries(extraPrefixesMap); + +type KeyMap = Map< + string, + | { + in: Slot; + map?: string; + } + | { + in?: never; + map: Slot; + } +>; + +const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { + if (!map) { + map = new Map(); + } + + for (const config of fields) { + if ('in' in config) { + if (config.key) { + map.set(config.key, { + in: config.in, + map: config.map, + }); + } + } else if ('key' in config) { + map.set(config.key, { + map: config.map, + }); + } else if (config.args) { + buildKeyMap(config.args, map); + } + } + + return map; +}; + +interface Params { + body: unknown; + headers: Record; + path: Record; + query: Record; +} + +const stripEmptySlots = (params: Params) => { + for (const [slot, value] of Object.entries(params)) { + if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { + delete params[slot as Slot]; + } + } +}; + +export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { + const params: Params = { + body: {}, + headers: {}, + path: {}, + query: {}, + }; + + const map = buildKeyMap(fields); + + let config: FieldsConfig[number] | undefined; + + for (const [index, arg] of args.entries()) { + if (fields[index]) { + config = fields[index]; + } + + if (!config) { + continue; + } + + if ('in' in config) { + if (config.key) { + const field = map.get(config.key)!; + const name = field.map || config.key; + if (field.in) { + (params[field.in] as Record)[name] = arg; + } + } else { + params.body = arg; + } + } else { + for (const [key, value] of Object.entries(arg ?? {})) { + const field = map.get(key); + + if (field) { + if (field.in) { + const name = field.map || key; + (params[field.in] as Record)[name] = value; + } else { + params[field.map] = value; + } + } else { + const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); + + if (extra) { + const [prefix, slot] = extra; + (params[slot] as Record)[key.slice(prefix.length)] = value; + } else if ('allowExtra' in config && config.allowExtra) { + for (const [slot, allowed] of Object.entries(config.allowExtra)) { + if (allowed) { + (params[slot as Slot] as Record)[key] = value; + break; + } + } + } + } + } + } + } + + stripEmptySlots(params); + + return params; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/pathSerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/pathSerializer.gen.ts new file mode 100644 index 0000000000..994b2848c6 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/pathSerializer.gen.ts @@ -0,0 +1,171 @@ +// This file is auto-generated by @hey-api/openapi-ts + +interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} + +interface SerializePrimitiveOptions { + allowReserved?: boolean; + name: string; +} + +export interface SerializerOptions { + /** + * @default true + */ + explode: boolean; + style: T; +} + +export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; +export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; +type MatrixStyle = 'label' | 'matrix' | 'simple'; +export type ObjectStyle = 'form' | 'deepObject'; +type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; + +interface SerializePrimitiveParam extends SerializePrimitiveOptions { + value: string; +} + +export const separatorArrayExplode = (style: ArraySeparatorStyle) => { + switch (style) { + case 'label': + return '.'; + case 'matrix': + return ';'; + case 'simple': + return ','; + default: + return '&'; + } +}; + +export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { + switch (style) { + case 'form': + return ','; + case 'pipeDelimited': + return '|'; + case 'spaceDelimited': + return '%20'; + default: + return ','; + } +}; + +export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { + switch (style) { + case 'label': + return '.'; + case 'matrix': + return ';'; + case 'simple': + return ','; + default: + return '&'; + } +}; + +export const serializeArrayParam = ({ + allowReserved, + explode, + name, + style, + value, +}: SerializeOptions & { + value: unknown[]; +}) => { + if (!explode) { + const joinedValues = ( + allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) + ).join(separatorArrayNoExplode(style)); + switch (style) { + case 'label': + return `.${joinedValues}`; + case 'matrix': + return `;${name}=${joinedValues}`; + case 'simple': + return joinedValues; + default: + return `${name}=${joinedValues}`; + } + } + + const separator = separatorArrayExplode(style); + const joinedValues = value + .map((v) => { + if (style === 'label' || style === 'simple') { + return allowReserved ? v : encodeURIComponent(v as string); + } + + return serializePrimitiveParam({ + allowReserved, + name, + value: v as string, + }); + }) + .join(separator); + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; +}; + +export const serializePrimitiveParam = ({ + allowReserved, + name, + value, +}: SerializePrimitiveParam) => { + if (value === undefined || value === null) { + return ''; + } + + if (typeof value === 'object') { + throw new Error( + 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', + ); + } + + return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; +}; + +export const serializeObjectParam = ({ + allowReserved, + explode, + name, + style, + value, + valueOnly, +}: SerializeOptions & { + value: Record | Date; + valueOnly?: boolean; +}) => { + if (value instanceof Date) { + return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; + } + + if (style !== 'deepObject' && !explode) { + let values: string[] = []; + Object.entries(value).forEach(([key, v]) => { + values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; + }); + const joinedValues = values.join(','); + switch (style) { + case 'form': + return `${name}=${joinedValues}`; + case 'label': + return `.${joinedValues}`; + case 'matrix': + return `;${name}=${joinedValues}`; + default: + return joinedValues; + } + } + + const separator = separatorObjectExplode(style); + const joinedValues = Object.entries(value) + .map(([key, v]) => + serializePrimitiveParam({ + allowReserved, + name: style === 'deepObject' ? `${name}[${key}]` : key, + value: v as string, + }), + ) + .join(separator); + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/queryKeySerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/queryKeySerializer.gen.ts new file mode 100644 index 0000000000..5000df606f --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/queryKeySerializer.gen.ts @@ -0,0 +1,117 @@ +// This file is auto-generated by @hey-api/openapi-ts + +/** + * JSON-friendly union that mirrors what Pinia Colada can hash. + */ +export type JsonValue = + | null + | string + | number + | boolean + | JsonValue[] + | { [key: string]: JsonValue }; + +/** + * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. + */ +export const queryKeyJsonReplacer = (_key: string, value: unknown) => { + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { + return undefined; + } + if (typeof value === 'bigint') { + return value.toString(); + } + if (value instanceof Date) { + return value.toISOString(); + } + return value; +}; + +/** + * Safely stringifies a value and parses it back into a JsonValue. + */ +export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { + try { + const json = JSON.stringify(input, queryKeyJsonReplacer); + if (json === undefined) { + return undefined; + } + return JSON.parse(json) as JsonValue; + } catch { + return undefined; + } +}; + +/** + * Detects plain objects (including objects with a null prototype). + */ +const isPlainObject = (value: unknown): value is Record => { + if (value === null || typeof value !== 'object') { + return false; + } + const prototype = Object.getPrototypeOf(value as object); + return prototype === Object.prototype || prototype === null; +}; + +/** + * Turns URLSearchParams into a sorted JSON object for deterministic keys. + */ +const serializeSearchParams = (params: URLSearchParams): JsonValue => { + const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); + const result: Record = {}; + + for (const [key, value] of entries) { + const existing = result[key]; + if (existing === undefined) { + result[key] = value; + continue; + } + + if (Array.isArray(existing)) { + (existing as string[]).push(value); + } else { + result[key] = [existing, value]; + } + } + + return result; +}; + +/** + * Normalizes any accepted value into a JSON-friendly shape for query keys. + */ +export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { + if (value === null) { + return null; + } + + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return value; + } + + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { + return undefined; + } + + if (typeof value === 'bigint') { + return value.toString(); + } + + if (value instanceof Date) { + return value.toISOString(); + } + + if (Array.isArray(value)) { + return stringifyToJsonValue(value); + } + + if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { + return serializeSearchParams(value); + } + + if (isPlainObject(value)) { + return stringifyToJsonValue(value); + } + + return undefined; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/serverSentEvents.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/serverSentEvents.gen.ts new file mode 100644 index 0000000000..6aa6cf02a4 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/serverSentEvents.gen.ts @@ -0,0 +1,243 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Config } from './types.gen'; + +export type ServerSentEventsOptions = Omit & + Pick & { + /** + * Fetch API implementation. You can use this option to provide a custom + * fetch instance. + * + * @default globalThis.fetch + */ + fetch?: typeof fetch; + /** + * Implementing clients can call request interceptors inside this hook. + */ + onRequest?: (url: string, init: RequestInit) => Promise; + /** + * Callback invoked when a network or parsing error occurs during streaming. + * + * This option applies only if the endpoint returns a stream of events. + * + * @param error The error that occurred. + */ + onSseError?: (error: unknown) => void; + /** + * Callback invoked when an event is streamed from the server. + * + * This option applies only if the endpoint returns a stream of events. + * + * @param event Event streamed from the server. + * @returns Nothing (void). + */ + onSseEvent?: (event: StreamEvent) => void; + serializedBody?: RequestInit['body']; + /** + * Default retry delay in milliseconds. + * + * This option applies only if the endpoint returns a stream of events. + * + * @default 3000 + */ + sseDefaultRetryDelay?: number; + /** + * Maximum number of retry attempts before giving up. + */ + sseMaxRetryAttempts?: number; + /** + * Maximum retry delay in milliseconds. + * + * Applies only when exponential backoff is used. + * + * This option applies only if the endpoint returns a stream of events. + * + * @default 30000 + */ + sseMaxRetryDelay?: number; + /** + * Optional sleep function for retry backoff. + * + * Defaults to using `setTimeout`. + */ + sseSleepFn?: (ms: number) => Promise; + url: string; + }; + +export interface StreamEvent { + data: TData; + event?: string; + id?: string; + retry?: number; +} + +export type ServerSentEventsResult = { + stream: AsyncGenerator< + TData extends Record ? TData[keyof TData] : TData, + TReturn, + TNext + >; +}; + +export const createSseClient = ({ + onRequest, + onSseError, + onSseEvent, + responseTransformer, + responseValidator, + sseDefaultRetryDelay, + sseMaxRetryAttempts, + sseMaxRetryDelay, + sseSleepFn, + url, + ...options +}: ServerSentEventsOptions): ServerSentEventsResult => { + let lastEventId: string | undefined; + + const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + + const createStream = async function* () { + let retryDelay: number = sseDefaultRetryDelay ?? 3000; + let attempt = 0; + const signal = options.signal ?? new AbortController().signal; + + while (true) { + if (signal.aborted) break; + + attempt++; + + const headers = + options.headers instanceof Headers + ? options.headers + : new Headers(options.headers as Record | undefined); + + if (lastEventId !== undefined) { + headers.set('Last-Event-ID', lastEventId); + } + + try { + const requestInit: RequestInit = { + redirect: 'follow', + ...options, + body: options.serializedBody, + headers, + signal, + }; + let request = new Request(url, requestInit); + if (onRequest) { + request = await onRequest(url, requestInit); + } + // fetch must be assigned here, otherwise it would throw the error: + // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation + const _fetch = options.fetch ?? globalThis.fetch; + const response = await _fetch(request); + + if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); + + if (!response.body) throw new Error('No body in SSE response'); + + const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); + + let buffer = ''; + + const abortHandler = () => { + try { + reader.cancel(); + } catch { + // noop + } + }; + + signal.addEventListener('abort', abortHandler); + + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + buffer += value; + // Normalize line endings: CRLF -> LF, then CR -> LF + buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); + + const chunks = buffer.split('\n\n'); + buffer = chunks.pop() ?? ''; + + for (const chunk of chunks) { + const lines = chunk.split('\n'); + const dataLines: Array = []; + let eventName: string | undefined; + + for (const line of lines) { + if (line.startsWith('data:')) { + dataLines.push(line.replace(/^data:\s*/, '')); + } else if (line.startsWith('event:')) { + eventName = line.replace(/^event:\s*/, ''); + } else if (line.startsWith('id:')) { + lastEventId = line.replace(/^id:\s*/, ''); + } else if (line.startsWith('retry:')) { + const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); + if (!Number.isNaN(parsed)) { + retryDelay = parsed; + } + } + } + + let data: unknown; + let parsedJson = false; + + if (dataLines.length) { + const rawData = dataLines.join('\n'); + try { + data = JSON.parse(rawData); + parsedJson = true; + } catch { + data = rawData; + } + } + + if (parsedJson) { + if (responseValidator) { + await responseValidator(data); + } + + if (responseTransformer) { + data = await responseTransformer(data); + } + } + + onSseEvent?.({ + data, + event: eventName, + id: lastEventId, + retry: retryDelay, + }); + + if (dataLines.length) { + yield data as any; + } + } + } + } finally { + signal.removeEventListener('abort', abortHandler); + reader.releaseLock(); + } + + break; // exit loop on normal completion + } catch (error) { + // connection failed or aborted; retry after delay + onSseError?.(error); + + if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { + break; // stop after firing error + } + + // exponential backoff: double retry each attempt, cap at 30s + const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); + await sleep(backoff); + } + } + }; + + const stream = createStream(); + + return { stream }; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/types.gen.ts new file mode 100644 index 0000000000..97463257e4 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/types.gen.ts @@ -0,0 +1,104 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Auth, AuthToken } from './auth.gen'; +import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; + +export type HttpMethod = + | 'connect' + | 'delete' + | 'get' + | 'head' + | 'options' + | 'patch' + | 'post' + | 'put' + | 'trace'; + +export type Client< + RequestFn = never, + Config = unknown, + MethodFn = never, + BuildUrlFn = never, + SseFn = never, +> = { + /** + * Returns the final request URL. + */ + buildUrl: BuildUrlFn; + getConfig: () => Config; + request: RequestFn; + setConfig: (config: Config) => Config; +} & { + [K in HttpMethod]: MethodFn; +} & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); + +export interface Config { + /** + * Auth token or a function returning auth token. The resolved value will be + * added to the request payload as defined by its `security` array. + */ + auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; + /** + * A function for serializing request body parameter. By default, + * {@link JSON.stringify()} will be used. + */ + bodySerializer?: BodySerializer | null; + /** + * An object containing any HTTP headers that you want to pre-populate your + * `Headers` object with. + * + * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} + */ + headers?: + | RequestInit['headers'] + | Record< + string, + string | number | boolean | (string | number | boolean)[] | null | undefined | unknown + >; + /** + * The request method. + * + * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} + */ + method?: Uppercase; + /** + * A function for serializing request query parameters. By default, arrays + * will be exploded in form style, objects will be exploded in deepObject + * style, and reserved characters are percent-encoded. + * + * This method will have no effect if the native `paramsSerializer()` Axios + * API function is used. + * + * {@link https://swagger.io/docs/specification/serialization/#query View examples} + */ + querySerializer?: QuerySerializer | QuerySerializerOptions; + /** + * A function validating request data. This is useful if you want to ensure + * the request conforms to the desired shape, so it can be safely sent to + * the server. + */ + requestValidator?: (data: unknown) => Promise; + /** + * A function transforming response data before it's returned. This is useful + * for post-processing data, e.g. converting ISO strings into Date objects. + */ + responseTransformer?: (data: unknown) => Promise; + /** + * A function validating response data. This is useful if you want to ensure + * the response conforms to the desired shape, so it can be safely passed to + * the transformers and returned to the user. + */ + responseValidator?: (data: unknown) => Promise; +} + +type IsExactlyNeverOrNeverUndefined = [T] extends [never] + ? true + : [T] extends [never | undefined] + ? [undefined] extends [T] + ? false + : true + : false; + +export type OmitNever> = { + [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/utils.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/utils.gen.ts new file mode 100644 index 0000000000..e7ddbe3541 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/core/utils.gen.ts @@ -0,0 +1,140 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; +import { + type ArraySeparatorStyle, + serializeArrayParam, + serializeObjectParam, + serializePrimitiveParam, +} from './pathSerializer.gen'; + +export interface PathSerializer { + path: Record; + url: string; +} + +export const PATH_PARAM_RE = /\{[^{}]+\}/g; + +export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { + let url = _url; + const matches = _url.match(PATH_PARAM_RE); + if (matches) { + for (const match of matches) { + let explode = false; + let name = match.substring(1, match.length - 1); + let style: ArraySeparatorStyle = 'simple'; + + if (name.endsWith('*')) { + explode = true; + name = name.substring(0, name.length - 1); + } + + if (name.startsWith('.')) { + name = name.substring(1); + style = 'label'; + } else if (name.startsWith(';')) { + name = name.substring(1); + style = 'matrix'; + } + + const value = path[name]; + + if (value === undefined || value === null) { + continue; + } + + if (Array.isArray(value)) { + url = url.replace(match, serializeArrayParam({ explode, name, style, value })); + continue; + } + + if (typeof value === 'object') { + url = url.replace( + match, + serializeObjectParam({ + explode, + name, + style, + value: value as Record, + valueOnly: true, + }), + ); + continue; + } + + if (style === 'matrix') { + url = url.replace( + match, + `;${serializePrimitiveParam({ + name, + value: value as string, + })}`, + ); + continue; + } + + const replaceValue = encodeURIComponent( + style === 'label' ? `.${value as string}` : (value as string), + ); + url = url.replace(match, replaceValue); + } + } + return url; +}; + +export const getUrl = ({ + baseUrl, + path, + query, + querySerializer, + url: _url, +}: { + baseUrl?: string; + path?: Record; + query?: Record; + querySerializer: QuerySerializer; + url: string; +}) => { + const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; + let url = (baseUrl ?? '') + pathUrl; + if (path) { + url = defaultPathSerializer({ path, url }); + } + let search = query ? querySerializer(query) : ''; + if (search.startsWith('?')) { + search = search.substring(1); + } + if (search) { + url += `?${search}`; + } + return url; +}; + +export function getValidRequestBody(options: { + body?: unknown; + bodySerializer?: BodySerializer | null; + serializedBody?: unknown; +}) { + const hasBody = options.body !== undefined; + const isSerializedBody = hasBody && options.bodySerializer; + + if (isSerializedBody) { + if ('serializedBody' in options) { + const hasSerializedBody = + options.serializedBody !== undefined && options.serializedBody !== ''; + + return hasSerializedBody ? options.serializedBody : null; + } + + // not all clients implement a serializedBody property (i.e. client-axios) + return options.body !== '' ? options.body : null; + } + + // plain/text body + if (hasBody) { + return options.body; + } + + // no body was provided + return undefined; +} diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/index.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/index.ts new file mode 100644 index 0000000000..6e132194fd --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/index.ts @@ -0,0 +1,4 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; +export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/sdk.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/sdk.gen.ts new file mode 100644 index 0000000000..e48dcff8cf --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/sdk.gen.ts @@ -0,0 +1,206 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; +import { client } from './client.gen'; +import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; + +export type Options = Options2 & { + /** + * You can provide a client instance returned by `createClient()` instead of + * individual options. This might be also useful if you want to implement a + * custom client. + */ + client?: Client; + /** + * You can pass arbitrary values through the `meta` object. This can be + * used to access values that aren't defined as part of the SDK function. + */ + meta?: Record; +}; + +export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); + +export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); + +export const import_ = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/no+tag', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); + +export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); + +export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); + +export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); + +export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); + +export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); + +export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); + +export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); + +export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); + +export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); + +export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); + +export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); + +/** + * @deprecated + */ +export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); + +export const callWithParameters = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/parameters/{parameterPath}', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ + url: '/api/v{api-version}/parameters', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/parameters', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ + url: '/api/v{api-version}/requestBody', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options?.headers + } +}); + +export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ + ...formDataBodySerializer, + url: '/api/v{api-version}/formData', + ...options, + headers: { + 'Content-Type': null, + ...options?.headers + } +}); + +export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); + +export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); + +export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); + +export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); + +export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); + +export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); + +export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); + +export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); + +export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); + +export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); + +export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); + +export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); + +export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); + +export const uploadFile = (options: Options) => (options.client ?? client).post({ + ...urlSearchParamsBodySerializer, + url: '/api/v{api-version}/upload', + ...options, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + ...options.headers + } +}); + +export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); + +export const complexTypes = (options: Options) => (options.client ?? client).get({ + querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, + url: '/api/v{api-version}/complex', + ...options +}); + +export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); + +export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ + ...formDataBodySerializer, + url: '/api/v{api-version}/multipart', + ...options, + headers: { + 'Content-Type': null, + ...options?.headers + } +}); + +export const complexParams = (options: Options) => (options.client ?? client).put({ + url: '/api/v{api-version}/complex/{id}', + ...options, + headers: { + 'Content-Type': 'application/json-patch+json', + ...options.headers + } +}); + +export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); + +export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); + +export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); + +/** + * Login User + */ +export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ + ...urlSearchParamsBodySerializer, + url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', + ...options, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + ...options.headers + } +}); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/types.gen.ts new file mode 100644 index 0000000000..3287ee8737 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/react-query/useQuery/types.gen.ts @@ -0,0 +1,2081 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type ClientOptions = { + baseUrl: 'http://localhost:3000/base' | (string & {}); +}; + +/** + * Model with number-only name + */ +export type _400 = string; + +export type ExternalRefA = ExternalSharedModel; + +export type ExternalRefB = ExternalSharedModel; + +/** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ +export type CamelCaseCommentWithBreaks = number; + +/** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ +export type CommentWithBreaks = number; + +/** + * Testing backticks in string: `backticks` and ```multiple backticks``` should work + */ +export type CommentWithBackticks = number; + +/** + * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work + */ +export type CommentWithBackticksAndQuotes = number; + +/** + * Testing slashes in string: \backwards\\\ and /forwards/// should work + */ +export type CommentWithSlashes = number; + +/** + * Testing expression placeholders in string: ${expression} should work + */ +export type CommentWithExpressionPlaceholders = number; + +/** + * Testing quotes in string: 'single quote''' and "double quotes""" should work + */ +export type CommentWithQuotes = number; + +/** + * Testing reserved characters in string: * inline * and ** inline ** should work + */ +export type CommentWithReservedCharacters = number; + +/** + * This is a simple number + */ +export type SimpleInteger = number; + +/** + * This is a simple boolean + */ +export type SimpleBoolean = boolean; + +/** + * This is a simple string + */ +export type SimpleString = string; + +/** + * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) + */ +export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; + +/** + * This is a simple file + */ +export type SimpleFile = Blob | File; + +/** + * This is a simple reference + */ +export type SimpleReference = ModelWithString; + +/** + * This is a simple string + */ +export type SimpleStringWithPattern = string | null; + +/** + * This is a simple enum with strings + */ +export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; + +export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; + +/** + * This is a simple enum with numbers + */ +export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; + +/** + * Success=1,Warning=2,Error=3 + */ +export type EnumFromDescription = number; + +/** + * This is a simple enum with numbers + */ +export type EnumWithExtensions = 200 | 400 | 500; + +export type EnumWithXEnumNames = 0 | 1 | 2; + +/** + * This is a simple array with numbers + */ +export type ArrayWithNumbers = Array; + +/** + * This is a simple array with booleans + */ +export type ArrayWithBooleans = Array; + +/** + * This is a simple array with strings + */ +export type ArrayWithStrings = Array; + +/** + * This is a simple array with references + */ +export type ArrayWithReferences = Array; + +/** + * This is a simple array containing an array + */ +export type ArrayWithArray = Array>; + +/** + * This is a simple array with properties + */ +export type ArrayWithProperties = Array<{ + '16x16'?: CamelCaseCommentWithBreaks; + bar?: string; +}>; + +/** + * This is a simple array with any of properties + */ +export type ArrayWithAnyOfProperties = Array<{ + foo?: string; +} | { + bar?: string; +}>; + +export type AnyOfAnyAndNull = { + data?: unknown; +}; + +/** + * This is a simple array with any of properties + */ +export type AnyOfArrays = { + results?: Array<{ + foo?: string; + } | { + bar?: string; + }>; +}; + +/** + * This is a string dictionary + */ +export type DictionaryWithString = { + [key: string]: string; +}; + +export type DictionaryWithPropertiesAndAdditionalProperties = { + foo?: number; + bar?: boolean; + [key: string]: string | number | boolean | undefined; +}; + +/** + * This is a string reference + */ +export type DictionaryWithReference = { + [key: string]: ModelWithString; +}; + +/** + * This is a complex dictionary + */ +export type DictionaryWithArray = { + [key: string]: Array; +}; + +/** + * This is a string dictionary + */ +export type DictionaryWithDictionary = { + [key: string]: { + [key: string]: string; + }; +}; + +/** + * This is a complex dictionary + */ +export type DictionaryWithProperties = { + [key: string]: { + foo?: string; + bar?: string; + }; +}; + +/** + * This is a model with one number property + */ +export type ModelWithInteger = { + /** + * This is a simple number property + */ + prop?: number; +}; + +/** + * This is a model with one boolean property + */ +export type ModelWithBoolean = { + /** + * This is a simple boolean property + */ + prop?: boolean; +}; + +/** + * This is a model with one string property + */ +export type ModelWithString = { + /** + * This is a simple string property + */ + prop?: string; +}; + +/** + * This is a model with one string property + */ +export type ModelWithStringError = { + /** + * This is a simple string property + */ + prop?: string; +}; + +/** + * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) + */ +export type ModelFromZendesk = string; + +/** + * This is a model with one string property + */ +export type ModelWithNullableString = { + /** + * This is a simple string property + */ + nullableProp1?: string | null; + /** + * This is a simple string property + */ + nullableRequiredProp1: string | null; + /** + * This is a simple string property + */ + nullableProp2?: string | null; + /** + * This is a simple string property + */ + nullableRequiredProp2: string | null; + /** + * This is a simple enum with strings + */ + 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; +}; + +/** + * This is a model with one enum + */ +export type ModelWithEnum = { + /** + * This is a simple enum with strings + */ + 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; + /** + * These are the HTTP error code enums + */ + statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; + /** + * Simple boolean enum + */ + bool?: true; +}; + +/** + * This is a model with one enum with escaped name + */ +export type ModelWithEnumWithHyphen = { + /** + * Foo-Bar-Baz-Qux + */ + 'foo-bar-baz-qux'?: '3.0'; +}; + +/** + * This is a model with one enum + */ +export type ModelWithEnumFromDescription = { + /** + * Success=1,Warning=2,Error=3 + */ + test?: number; +}; + +/** + * This is a model with nested enums + */ +export type ModelWithNestedEnums = { + dictionaryWithEnum?: { + [key: string]: 'Success' | 'Warning' | 'Error'; + }; + dictionaryWithEnumFromDescription?: { + [key: string]: number; + }; + arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; + arrayWithDescription?: Array; + /** + * This is a simple enum with strings + */ + 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; +}; + +/** + * This is a model with one property containing a reference + */ +export type ModelWithReference = { + prop?: ModelWithProperties; +}; + +/** + * This is a model with one property containing an array + */ +export type ModelWithArrayReadOnlyAndWriteOnly = { + prop?: Array; + propWithFile?: Array; + propWithNumber?: Array; +}; + +/** + * This is a model with one property containing an array + */ +export type ModelWithArray = { + prop?: Array; + propWithFile?: Array; + propWithNumber?: Array; +}; + +/** + * This is a model with one property containing a dictionary + */ +export type ModelWithDictionary = { + prop?: { + [key: string]: string; + }; +}; + +/** + * This is a deprecated model with a deprecated property + * + * @deprecated + */ +export type DeprecatedModel = { + /** + * This is a deprecated property + * + * @deprecated + */ + prop?: string; +}; + +/** + * This is a model with one property containing a circular reference + */ +export type ModelWithCircularReference = { + prop?: ModelWithCircularReference; +}; + +/** + * This is a model with one property with a 'one of' relationship + */ +export type CompositionWithOneOf = { + propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; +}; + +/** + * This is a model with one property with a 'one of' relationship where the options are not $ref + */ +export type CompositionWithOneOfAnonymous = { + propA?: { + propA?: string; + } | string | number; +}; + +/** + * Circle + */ +export type ModelCircle = { + kind: string; + radius?: number; +}; + +/** + * Square + */ +export type ModelSquare = { + kind: string; + sideLength?: number; +}; + +/** + * This is a model with one property with a 'one of' relationship where the options are not $ref + */ +export type CompositionWithOneOfDiscriminator = ({ + kind: 'circle'; +} & ModelCircle) | ({ + kind: 'square'; +} & ModelSquare); + +/** + * This is a model with one property with a 'any of' relationship + */ +export type CompositionWithAnyOf = { + propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; +}; + +/** + * This is a model with one property with a 'any of' relationship where the options are not $ref + */ +export type CompositionWithAnyOfAnonymous = { + propA?: { + propA?: string; + } | string | number; +}; + +/** + * This is a model with nested 'any of' property with a type null + */ +export type CompositionWithNestedAnyAndTypeNull = { + propA?: Array | Array; +}; + +export type _3eNum1Период = 'Bird' | 'Dog'; + +export type ConstValue = 'ConstValue'; + +/** + * This is a model with one property with a 'any of' relationship where the options are not $ref + */ +export type CompositionWithNestedAnyOfAndNull = { + propA?: Array<_3eNum1Период | ConstValue> | null; +}; + +/** + * This is a model with one property with a 'one of' relationship + */ +export type CompositionWithOneOfAndNullable = { + propA?: { + boolean?: boolean; + } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; +}; + +/** + * This is a model that contains a simple dictionary within composition + */ +export type CompositionWithOneOfAndSimpleDictionary = { + propA?: boolean | { + [key: string]: number; + }; +}; + +/** + * This is a model that contains a dictionary of simple arrays within composition + */ +export type CompositionWithOneOfAndSimpleArrayDictionary = { + propA?: boolean | { + [key: string]: Array; + }; +}; + +/** + * This is a model that contains a dictionary of complex arrays (composited) within composition + */ +export type CompositionWithOneOfAndComplexArrayDictionary = { + propA?: boolean | { + [key: string]: Array; + }; +}; + +/** + * This is a model with one property with a 'all of' relationship + */ +export type CompositionWithAllOfAndNullable = { + propA?: ({ + boolean?: boolean; + } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; +}; + +/** + * This is a model with one property with a 'any of' relationship + */ +export type CompositionWithAnyOfAndNullable = { + propA?: { + boolean?: boolean; + } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; +}; + +/** + * This is a base model with two simple optional properties + */ +export type CompositionBaseModel = { + firstName?: string; + lastname?: string; +}; + +/** + * This is a model that extends the base model + */ +export type CompositionExtendedModel = CompositionBaseModel & { + age: number; + firstName: string; + lastname: string; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithProperties = { + required: string; + readonly requiredAndReadOnly: string; + requiredAndNullable: string | null; + string?: string; + number?: number; + boolean?: boolean; + reference?: ModelWithString; + 'property with space'?: string; + default?: string; + try?: string; + readonly '@namespace.string'?: string; + readonly '@namespace.integer'?: number; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithNestedProperties = { + readonly first: { + readonly second: { + readonly third: string | null; + } | null; + } | null; +}; + +/** + * This is a model with duplicated properties + */ +export type ModelWithDuplicateProperties = { + prop?: ModelWithString; +}; + +/** + * This is a model with ordered properties + */ +export type ModelWithOrderedProperties = { + zebra?: string; + apple?: string; + hawaii?: string; +}; + +/** + * This is a model with duplicated imports + */ +export type ModelWithDuplicateImports = { + propA?: ModelWithString; + propB?: ModelWithString; + propC?: ModelWithString; +}; + +/** + * This is a model that extends another model + */ +export type ModelThatExtends = ModelWithString & { + propExtendsA?: string; + propExtendsB?: ModelWithString; +}; + +/** + * This is a model that extends another model + */ +export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { + propExtendsC?: string; + propExtendsD?: ModelWithString; +}; + +/** + * This is a model that contains a some patterns + */ +export type ModelWithPattern = { + key: string; + name: string; + readonly enabled?: boolean; + readonly modified?: string; + id?: string; + text?: string; + patternWithSingleQuotes?: string; + patternWithNewline?: string; + patternWithBacktick?: string; + patternWithUnicode?: string; +}; + +export type File = { + /** + * Id + */ + readonly id?: string; + /** + * Updated at + */ + readonly updated_at?: string; + /** + * Created at + */ + readonly created_at?: string; + /** + * Mime + */ + mime: string; + /** + * File + */ + readonly file?: string; +}; + +export type Default = { + name?: string; +}; + +export type Pageable = { + page?: number; + size?: number; + sort?: Array; +}; + +/** + * This is a free-form object without additionalProperties. + */ +export type FreeFormObjectWithoutAdditionalProperties = { + [key: string]: unknown; +}; + +/** + * This is a free-form object with additionalProperties: true. + */ +export type FreeFormObjectWithAdditionalPropertiesEqTrue = { + [key: string]: unknown; +}; + +/** + * This is a free-form object with additionalProperties: {}. + */ +export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { + [key: string]: unknown; +}; + +export type ModelWithConst = { + String?: 'String'; + number?: 0; + null?: unknown; + withType?: 'Some string'; +}; + +/** + * This is a model with one property and additionalProperties: true + */ +export type ModelWithAdditionalPropertiesEqTrue = { + /** + * This is a simple string property + */ + prop?: string; + [key: string]: unknown; +}; + +export type NestedAnyOfArraysNullable = { + nullableArray?: Array | null; +}; + +export type CompositionWithOneOfAndProperties = ({ + foo: SimpleParameter; +} | { + bar: NonAsciiStringæøåÆøÅöôêÊ字符串; +}) & { + baz: number | null; + qux: number; +}; + +/** + * An object that can be null + */ +export type NullableObject = { + foo?: string; +} | null; + +/** + * Some % character + */ +export type CharactersInDescription = string; + +export type ModelWithNullableObject = { + data?: NullableObject; +}; + +/** + * An object with additional properties that can be null + */ +export type ModelWithAdditionalPropertiesRef = { + [key: string]: NullableObject | null; +}; + +export type ModelWithOneOfEnum = { + foo: 'Bar'; +} | { + foo: 'Baz'; +} | { + foo: 'Qux'; +} | { + content: string; + foo: 'Quux'; +} | { + content: [ + string, + string + ]; + foo: 'Corge'; +}; + +export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; + +export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; + +export type ModelWithNestedArrayEnumsData = { + foo?: Array; + bar?: Array; +}; + +export type ModelWithNestedArrayEnums = { + array_strings?: Array; + data?: ModelWithNestedArrayEnumsData; +}; + +export type ModelWithNestedCompositionEnums = { + foo?: ModelWithNestedArrayEnumsDataFoo; +}; + +export type ModelWithReadOnlyAndWriteOnly = { + foo: string; + readonly bar: string; +}; + +export type ModelWithConstantSizeArray = [ + number, + number +]; + +export type ModelWithAnyOfConstantSizeArray = [ + number | string, + number | string, + number | string +]; + +export type ModelWithPrefixItemsConstantSizeArray = Array; + +export type ModelWithAnyOfConstantSizeArrayNullable = [ + number | null | string, + number | null | string, + number | null | string +]; + +export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ + number | Import, + number | Import +]; + +export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ + number & string, + number & string +]; + +export type ModelWithNumericEnumUnion = { + /** + * Период + */ + value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; +}; + +/** + * Some description with `back ticks` + */ +export type ModelWithBackticksInDescription = { + /** + * The template `that` should be used for parsing and importing the contents of the CSV file. + * + *

There is one placeholder currently supported:

  • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

Example of a correct JSON template:

+ *
+     * [
+     * {
+     * "resourceType": "Asset",
+     * "identifier": {
+     * "name": "${1}",
+     * "domain": {
+     * "name": "${2}",
+     * "community": {
+     * "name": "Some Community"
+     * }
+     * }
+     * },
+     * "attributes" : {
+     * "00000000-0000-0000-0000-000000003115" : [ {
+     * "value" : "${3}"
+     * } ],
+     * "00000000-0000-0000-0000-000000000222" : [ {
+     * "value" : "${4}"
+     * } ]
+     * }
+     * }
+     * ]
+     * 
+ */ + template?: string; +}; + +export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { + baz: number | null; + qux: number; +}; + +/** + * Model used to test deduplication strategy (unused) + */ +export type ParameterSimpleParameterUnused = string; + +/** + * Model used to test deduplication strategy + */ +export type PostServiceWithEmptyTagResponse = string; + +/** + * Model used to test deduplication strategy + */ +export type PostServiceWithEmptyTagResponse2 = string; + +/** + * Model used to test deduplication strategy + */ +export type DeleteFooData = string; + +/** + * Model used to test deduplication strategy + */ +export type DeleteFooData2 = string; + +/** + * Model with restricted keyword name + */ +export type Import = string; + +export type SchemaWithFormRestrictedKeys = { + description?: string; + 'x-enum-descriptions'?: string; + 'x-enum-varnames'?: string; + 'x-enumNames'?: string; + title?: string; + object?: { + description?: string; + 'x-enum-descriptions'?: string; + 'x-enum-varnames'?: string; + 'x-enumNames'?: string; + title?: string; + }; + array?: Array<{ + description?: string; + 'x-enum-descriptions'?: string; + 'x-enum-varnames'?: string; + 'x-enumNames'?: string; + title?: string; + }>; +}; + +/** + * This schema was giving PascalCase transformations a hard time + */ +export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { + /** + * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. + */ + preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; +}; + +/** + * This schema was giving PascalCase transformations a hard time + */ +export type IoK8sApimachineryPkgApisMetaV1Preconditions = { + /** + * Specifies the target ResourceVersion + */ + resourceVersion?: string; + /** + * Specifies the target UID. + */ + uid?: string; +}; + +export type AdditionalPropertiesUnknownIssue = { + [key: string]: string | number; +}; + +export type AdditionalPropertiesUnknownIssue2 = { + [key: string]: string | number; +}; + +export type AdditionalPropertiesUnknownIssue3 = string & { + entries: { + [key: string]: AdditionalPropertiesUnknownIssue; + }; +}; + +export type AdditionalPropertiesIntegerIssue = { + value: number; + [key: string]: number; +}; + +export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; + +export type GenericSchemaDuplicateIssue1SystemBoolean = { + item?: boolean; + error?: string | null; + readonly hasError?: boolean; + data?: { + [key: string]: never; + }; +}; + +export type GenericSchemaDuplicateIssue1SystemString = { + item?: string | null; + error?: string | null; + readonly hasError?: boolean; +}; + +export type ExternalSharedModel = { + id: string; + name?: string; +}; + +/** + * This is a model with one property containing a reference + */ +export type ModelWithReferenceWritable = { + prop?: ModelWithPropertiesWritable; +}; + +/** + * This is a model with one property containing an array + */ +export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { + prop?: Array; + propWithFile?: Array; + propWithNumber?: Array; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithPropertiesWritable = { + required: string; + requiredAndNullable: string | null; + string?: string; + number?: number; + boolean?: boolean; + reference?: ModelWithString; + 'property with space'?: string; + default?: string; + try?: string; +}; + +/** + * This is a model that contains a some patterns + */ +export type ModelWithPatternWritable = { + key: string; + name: string; + id?: string; + text?: string; + patternWithSingleQuotes?: string; + patternWithNewline?: string; + patternWithBacktick?: string; + patternWithUnicode?: string; +}; + +export type FileWritable = { + /** + * Mime + */ + mime: string; +}; + +export type ModelWithReadOnlyAndWriteOnlyWritable = { + foo: string; + baz: string; +}; + +export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ + number | Import, + number | Import +]; + +export type AdditionalPropertiesUnknownIssueWritable = { + [key: string]: string | number; +}; + +export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; + +export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { + item?: boolean; + error?: string | null; + data?: { + [key: string]: never; + }; +}; + +export type GenericSchemaDuplicateIssue1SystemStringWritable = { + item?: string | null; + error?: string | null; +}; + +/** + * This is a reusable parameter + */ +export type SimpleParameter = string; + +/** + * Parameter with illegal characters + */ +export type XFooBar = ModelWithString; + +export type SimpleRequestBody = ModelWithString; + +export type SimpleFormData = ModelWithString; + +export type ExportData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type PatchApiVbyApiVersionNoTagData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type PatchApiVbyApiVersionNoTagResponses = { + /** + * OK + */ + default: unknown; +}; + +export type ImportData = { + body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type ImportResponses = { + /** + * Success + */ + 200: ModelFromZendesk; + /** + * Default success response + */ + default: ModelWithReadOnlyAndWriteOnly; +}; + +export type ImportResponse = ImportResponses[keyof ImportResponses]; + +export type FooWowData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type FooWowResponses = { + /** + * OK + */ + default: unknown; +}; + +export type ApiVVersionODataControllerCountData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple/$count'; +}; + +export type ApiVVersionODataControllerCountResponses = { + /** + * Success + */ + 200: ModelFromZendesk; +}; + +export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; + +export type GetApiVbyApiVersionSimpleOperationData = { + body?: never; + path: { + /** + * foo in method + */ + foo_param: string; + }; + query?: never; + url: '/api/v{api-version}/simple:operation'; +}; + +export type GetApiVbyApiVersionSimpleOperationErrors = { + /** + * Default error response + */ + default: ModelWithBoolean; +}; + +export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; + +export type GetApiVbyApiVersionSimpleOperationResponses = { + /** + * Response is a simple number + */ + 200: number; +}; + +export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; + +export type DeleteCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type GetCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type HeadCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type OptionsCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PatchCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PostCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PutCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type DeleteFooData3 = { + body?: never; + headers: { + /** + * Parameter with illegal characters + */ + 'x-Foo-Bar': ModelWithString; + }; + path: { + /** + * foo in method + */ + foo_param: string; + /** + * bar in method + */ + BarParam: string; + }; + query?: never; + url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; +}; + +export type CallWithDescriptionsData = { + body?: never; + path?: never; + query?: { + /** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ + parameterWithBreaks?: string; + /** + * Testing backticks in string: `backticks` and ```multiple backticks``` should work + */ + parameterWithBackticks?: string; + /** + * Testing slashes in string: \backwards\\\ and /forwards/// should work + */ + parameterWithSlashes?: string; + /** + * Testing expression placeholders in string: ${expression} should work + */ + parameterWithExpressionPlaceholders?: string; + /** + * Testing quotes in string: 'single quote''' and "double quotes""" should work + */ + parameterWithQuotes?: string; + /** + * Testing reserved characters in string: * inline * and ** inline ** should work + */ + parameterWithReservedCharacters?: string; + }; + url: '/api/v{api-version}/descriptions'; +}; + +export type DeprecatedCallData = { + body?: never; + headers: { + /** + * This parameter is deprecated + * + * @deprecated + */ + parameter: DeprecatedModel | null; + }; + path?: never; + query?: never; + url: '/api/v{api-version}/parameters/deprecated'; +}; + +export type CallWithParametersData = { + /** + * This is the parameter that goes into the body + */ + body: { + [key: string]: unknown; + } | null; + headers: { + /** + * This is the parameter that goes into the header + */ + parameterHeader: string | null; + }; + path: { + /** + * This is the parameter that goes into the path + */ + parameterPath: string | null; + /** + * api-version should be required in standalone clients + */ + 'api-version': string | null; + }; + query: { + foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; + foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; + /** + * This is the parameter that goes into the query params + */ + cursor: string | null; + }; + url: '/api/v{api-version}/parameters/{parameterPath}'; +}; + +export type CallWithWeirdParameterNamesData = { + /** + * This is the parameter that goes into the body + */ + body: ModelWithString | null; + headers: { + /** + * This is the parameter that goes into the request header + */ + 'parameter.header': string | null; + }; + path: { + /** + * This is the parameter that goes into the path + */ + 'parameter.path.1'?: string; + /** + * This is the parameter that goes into the path + */ + 'parameter-path-2'?: string; + /** + * This is the parameter that goes into the path + */ + 'PARAMETER-PATH-3'?: string; + /** + * api-version should be required in standalone clients + */ + 'api-version': string | null; + }; + query: { + /** + * This is the parameter with a reserved keyword + */ + default?: string; + /** + * This is the parameter that goes into the request query params + */ + 'parameter-query': string | null; + }; + url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; +}; + +export type GetCallWithOptionalParamData = { + /** + * This is a required parameter + */ + body: ModelWithOneOfEnum; + path?: never; + query?: { + /** + * This is an optional parameter + */ + page?: number; + }; + url: '/api/v{api-version}/parameters'; +}; + +export type PostCallWithOptionalParamData = { + /** + * This is an optional parameter + */ + body?: { + offset?: number | null; + }; + path?: never; + query: { + /** + * This is a required parameter + */ + parameter: Pageable; + }; + url: '/api/v{api-version}/parameters'; +}; + +export type PostCallWithOptionalParamResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Success + */ + 204: void; +}; + +export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; + +export type PostApiVbyApiVersionRequestBodyData = { + /** + * A reusable request body + */ + body?: SimpleRequestBody; + path?: never; + query?: { + /** + * This is a reusable parameter + */ + parameter?: string; + }; + url: '/api/v{api-version}/requestBody'; +}; + +export type PostApiVbyApiVersionFormDataData = { + /** + * A reusable request body + */ + body?: SimpleFormData; + path?: never; + query?: { + /** + * This is a reusable parameter + */ + parameter?: string; + }; + url: '/api/v{api-version}/formData'; +}; + +export type CallWithDefaultParametersData = { + body?: never; + path?: never; + query?: { + /** + * This is a simple string with default value + */ + parameterString?: string | null; + /** + * This is a simple number with default value + */ + parameterNumber?: number | null; + /** + * This is a simple boolean with default value + */ + parameterBoolean?: boolean | null; + /** + * This is a simple enum with default value + */ + parameterEnum?: 'Success' | 'Warning' | 'Error'; + /** + * This is a simple model with default value + */ + parameterModel?: ModelWithString | null; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type CallWithDefaultOptionalParametersData = { + body?: never; + path?: never; + query?: { + /** + * This is a simple string that is optional with default value + */ + parameterString?: string; + /** + * This is a simple number that is optional with default value + */ + parameterNumber?: number; + /** + * This is a simple boolean that is optional with default value + */ + parameterBoolean?: boolean; + /** + * This is a simple enum that is optional with default value + */ + parameterEnum?: 'Success' | 'Warning' | 'Error'; + /** + * This is a simple model that is optional with default value + */ + parameterModel?: ModelWithString; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type CallToTestOrderOfParamsData = { + body?: never; + path?: never; + query: { + /** + * This is a optional string with default + */ + parameterOptionalStringWithDefault?: string; + /** + * This is a optional string with empty default + */ + parameterOptionalStringWithEmptyDefault?: string; + /** + * This is a optional string with no default + */ + parameterOptionalStringWithNoDefault?: string; + /** + * This is a string with default + */ + parameterStringWithDefault: string; + /** + * This is a string with empty default + */ + parameterStringWithEmptyDefault: string; + /** + * This is a string with no default + */ + parameterStringWithNoDefault: string; + /** + * This is a string that can be null with no default + */ + parameterStringNullableWithNoDefault?: string | null; + /** + * This is a string that can be null with default + */ + parameterStringNullableWithDefault?: string | null; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type DuplicateNameData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName2Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName3Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName4Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type CallWithNoContentResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no-content'; +}; + +export type CallWithNoContentResponseResponses = { + /** + * Success + */ + 204: void; +}; + +export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; + +export type CallWithResponseAndNoContentResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/response-and-no-content'; +}; + +export type CallWithResponseAndNoContentResponseResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Success + */ + 204: void; +}; + +export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; + +export type DummyAData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/a'; +}; + +export type DummyAResponses = { + 200: _400; +}; + +export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; + +export type DummyBData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/b'; +}; + +export type DummyBResponses = { + /** + * Success + */ + 204: void; +}; + +export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; + +export type CallWithResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithResponseResponses = { + default: Import; +}; + +export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; + +export type CallWithDuplicateResponsesData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithDuplicateResponsesErrors = { + /** + * Message for 500 error + */ + 500: ModelWithStringError; + /** + * Message for 501 error + */ + 501: ModelWithStringError; + /** + * Message for 502 error + */ + 502: ModelWithStringError; + /** + * Message for 4XX errors + */ + '4XX': DictionaryWithArray; + /** + * Default error response + */ + default: ModelWithBoolean; +}; + +export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; + +export type CallWithDuplicateResponsesResponses = { + /** + * Message for 200 response + */ + 200: ModelWithBoolean & ModelWithInteger; + /** + * Message for 201 response + */ + 201: ModelWithString; + /** + * Message for 202 response + */ + 202: ModelWithString; +}; + +export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; + +export type CallWithResponsesData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithResponsesErrors = { + /** + * Message for 500 error + */ + 500: ModelWithStringError; + /** + * Message for 501 error + */ + 501: ModelWithStringError; + /** + * Message for 502 error + */ + 502: ModelWithStringError; + /** + * Message for default response + */ + default: ModelWithStringError; +}; + +export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; + +export type CallWithResponsesResponses = { + /** + * Message for 200 response + */ + 200: { + readonly '@namespace.string'?: string; + readonly '@namespace.integer'?: number; + readonly value?: Array; + }; + /** + * Message for 201 response + */ + 201: ModelThatExtends; + /** + * Message for 202 response + */ + 202: ModelThatExtendsExtends; +}; + +export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; + +export type CollectionFormatData = { + body?: never; + path?: never; + query: { + /** + * This is an array parameter that is sent as csv format (comma-separated values) + */ + parameterArrayCSV: Array | null; + /** + * This is an array parameter that is sent as ssv format (space-separated values) + */ + parameterArraySSV: Array | null; + /** + * This is an array parameter that is sent as tsv format (tab-separated values) + */ + parameterArrayTSV: Array | null; + /** + * This is an array parameter that is sent as pipes format (pipe-separated values) + */ + parameterArrayPipes: Array | null; + /** + * This is an array parameter that is sent as multi format (multiple parameter instances) + */ + parameterArrayMulti: Array | null; + }; + url: '/api/v{api-version}/collectionFormat'; +}; + +export type TypesData = { + body?: never; + path?: { + /** + * This is a number parameter + */ + id?: number; + }; + query: { + /** + * This is a number parameter + */ + parameterNumber: number; + /** + * This is a string parameter + */ + parameterString: string | null; + /** + * This is a boolean parameter + */ + parameterBoolean: boolean | null; + /** + * This is an object parameter + */ + parameterObject: { + [key: string]: unknown; + } | null; + /** + * This is an array parameter + */ + parameterArray: Array | null; + /** + * This is a dictionary parameter + */ + parameterDictionary: { + [key: string]: unknown; + } | null; + /** + * This is an enum parameter + */ + parameterEnum: 'Success' | 'Warning' | 'Error'; + }; + url: '/api/v{api-version}/types'; +}; + +export type TypesResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Response is a simple string + */ + 201: string; + /** + * Response is a simple boolean + */ + 202: boolean; + /** + * Response is a simple object + */ + 203: { + [key: string]: unknown; + }; +}; + +export type TypesResponse = TypesResponses[keyof TypesResponses]; + +export type UploadFileData = { + body: Blob | File; + path: { + /** + * api-version should be required in standalone clients + */ + 'api-version': string | null; + }; + query?: never; + url: '/api/v{api-version}/upload'; +}; + +export type UploadFileResponses = { + 200: boolean; +}; + +export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; + +export type FileResponseData = { + body?: never; + path: { + id: string; + /** + * api-version should be required in standalone clients + */ + 'api-version': string; + }; + query?: never; + url: '/api/v{api-version}/file/{id}'; +}; + +export type FileResponseResponses = { + /** + * Success + */ + 200: Blob | File; +}; + +export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; + +export type ComplexTypesData = { + body?: never; + path?: never; + query: { + /** + * Parameter containing object + */ + parameterObject: { + first?: { + second?: { + third?: string; + }; + }; + }; + /** + * Parameter containing reference + */ + parameterReference: ModelWithString; + }; + url: '/api/v{api-version}/complex'; +}; + +export type ComplexTypesErrors = { + /** + * 400 `server` error + */ + 400: unknown; + /** + * 500 server error + */ + 500: unknown; +}; + +export type ComplexTypesResponses = { + /** + * Successful response + */ + 200: Array; +}; + +export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; + +export type MultipartResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multipart'; +}; + +export type MultipartResponseResponses = { + /** + * OK + */ + 200: { + file?: Blob | File; + metadata?: { + foo?: string; + bar?: string; + }; + }; +}; + +export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; + +export type MultipartRequestData = { + body?: { + content?: Blob | File; + data?: ModelWithString | null; + }; + path?: never; + query?: never; + url: '/api/v{api-version}/multipart'; +}; + +export type ComplexParamsData = { + body?: { + readonly key: string | null; + name: string | null; + enabled?: boolean; + type: 'Monkey' | 'Horse' | 'Bird'; + listOfModels?: Array | null; + listOfStrings?: Array | null; + parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; + readonly user?: { + readonly id?: number; + readonly name?: string | null; + }; + }; + path: { + id: number; + /** + * api-version should be required in standalone clients + */ + 'api-version': string; + }; + query?: never; + url: '/api/v{api-version}/complex/{id}'; +}; + +export type ComplexParamsResponses = { + /** + * Success + */ + 200: ModelWithString; +}; + +export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; + +export type CallWithResultFromHeaderData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/header'; +}; + +export type CallWithResultFromHeaderErrors = { + /** + * 400 server error + */ + 400: unknown; + /** + * 500 server error + */ + 500: unknown; +}; + +export type CallWithResultFromHeaderResponses = { + /** + * Successful response + */ + 200: unknown; +}; + +export type TestErrorCodeData = { + body?: never; + path?: never; + query: { + /** + * Status code to return + */ + status: number; + }; + url: '/api/v{api-version}/error'; +}; + +export type TestErrorCodeErrors = { + /** + * Custom message: Internal Server Error + */ + 500: unknown; + /** + * Custom message: Not Implemented + */ + 501: unknown; + /** + * Custom message: Bad Gateway + */ + 502: unknown; + /** + * Custom message: Service Unavailable + */ + 503: unknown; +}; + +export type TestErrorCodeResponses = { + /** + * Custom message: Successful response + */ + 200: unknown; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Data = { + body?: never; + path?: never; + query: { + /** + * Dummy input param + */ + nonAsciiParamæøåÆØÅöôêÊ: number; + }; + url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { + /** + * Successful response + */ + 200: Array; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; + +export type PutWithFormUrlEncodedData = { + body: ArrayWithStrings; + path?: never; + query?: never; + url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/asClass/@tanstack/solid-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/asClass/@tanstack/solid-query.gen.ts index d5594064cc..4c3bc16520 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/asClass/@tanstack/solid-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/asClass/@tanstack/solid-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/solid-query'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/solid-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooOptions = (options?: Options) => queryOptions>): MutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutMutation = (options?: Partial>): Mutation export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarOptions = (options?: Options) => queryOptio throwOnError: true }); return data; - }, - queryKey: getFooBarQueryKey(options) + }), + queryKey: getFooBarQueryKey(resolveOptions(options)) }); export const fooBarPostMutation = (options?: Partial>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/axios/@tanstack/solid-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/axios/@tanstack/solid-query.gen.ts index 203534a865..d69126c7cb 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/axios/@tanstack/solid-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/axios/@tanstack/solid-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/solid-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions, skipToken } from '@tanstack/solid-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; @@ -40,10 +40,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -51,8 +55,8 @@ export const exportOptions = (options?: Options) => queryOptions>): MutationOptions, Options> => { @@ -99,8 +103,8 @@ export const fooWowMutation = (options?: Partial>): Mutation export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -108,14 +112,14 @@ export const apiVVersionODataControllerCountOptions = (options?: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -123,8 +127,8 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options>): MutationOptions, Options> => { @@ -143,8 +147,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -152,8 +156,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): MutationOptions, Options> => { @@ -273,8 +277,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -282,8 +286,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -317,10 +321,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -335,8 +339,8 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options>): MutationOptions, Options> => { @@ -383,8 +387,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -392,8 +396,8 @@ export const callWithDefaultParametersOptions = (options?: Options>): MutationOptions, Options> => { @@ -440,8 +444,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -449,8 +453,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions, Options> => { @@ -483,8 +487,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -492,14 +496,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -507,14 +511,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions, DummyAResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -522,14 +526,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions, DummyBResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -537,14 +541,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -552,8 +556,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions, Options> => { @@ -586,8 +590,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -595,14 +599,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions, TypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -610,8 +614,8 @@ export const typesOptions = (options: Options) => queryOptions>): MutationOptions, Options> => { @@ -630,8 +634,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions, FileResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -639,14 +643,14 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions, ComplexTypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -654,14 +658,14 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions, MultipartResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -669,8 +673,8 @@ export const multipartResponseOptions = (options?: Options>): MutationOptions, Options> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/fetch/@tanstack/solid-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/fetch/@tanstack/solid-query.gen.ts index 358caac28f..5bbeeb813b 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/fetch/@tanstack/solid-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/fetch/@tanstack/solid-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/solid-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions, skipToken } from '@tanstack/solid-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const exportOptions = (options?: Options) => queryOptions>): MutationOptions> => { @@ -98,8 +102,8 @@ export const fooWowMutation = (options?: Partial>): Mutation export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -107,14 +111,14 @@ export const apiVVersionODataControllerCountOptions = (options?: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -122,8 +126,8 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options>): MutationOptions> => { @@ -142,8 +146,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -151,8 +155,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): MutationOptions> => { @@ -272,8 +276,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -281,8 +285,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -316,10 +320,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -334,8 +338,8 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options>): MutationOptions> => { @@ -382,8 +386,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -391,8 +395,8 @@ export const callWithDefaultParametersOptions = (options?: Options>): MutationOptions> => { @@ -439,8 +443,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -448,8 +452,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions> => { @@ -482,8 +486,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -491,14 +495,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -506,14 +510,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -521,14 +525,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -536,14 +540,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -551,8 +555,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions> => { @@ -585,8 +589,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -594,14 +598,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -609,8 +613,8 @@ export const typesOptions = (options: Options) => queryOptions>): MutationOptions> => { @@ -629,8 +633,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -638,14 +642,14 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -653,14 +657,14 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -668,8 +672,8 @@ export const multipartResponseOptions = (options?: Options>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/name-builder/@tanstack/solid-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/name-builder/@tanstack/solid-query.gen.ts index ba1febdda4..c7ec98152f 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/name-builder/@tanstack/solid-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/solid-query/name-builder/@tanstack/solid-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/solid-query'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/solid-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooD = (options?: Options) => createQueryKey('getFoo', options); -export const getFooE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooE = (options?: Options) => queryOptions>): MutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutC = (options?: Partial>): MutationOptions export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarE = (options?: Options) => queryOptions>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/asClass/@tanstack/svelte-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/asClass/@tanstack/svelte-query.gen.ts index 3e29275971..af19b9b3eb 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/asClass/@tanstack/svelte-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/asClass/@tanstack/svelte-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/svelte-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooOptions = (options?: Options) => queryOptions>): MutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutMutation = (options?: Partial>): Mutation export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarOptions = (options?: Options) => queryOptio throwOnError: true }); return data; - }, - queryKey: getFooBarQueryKey(options) + }), + queryKey: getFooBarQueryKey(resolveOptions(options)) }); export const fooBarPostMutation = (options?: Partial>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/axios/@tanstack/svelte-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/axios/@tanstack/svelte-query.gen.ts index 9e78e66d27..58d7b73904 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/axios/@tanstack/svelte-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/axios/@tanstack/svelte-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions, skipToken } from '@tanstack/svelte-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; @@ -40,10 +40,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -51,8 +55,8 @@ export const exportOptions = (options?: Options) => queryOptions>): MutationOptions, Options> => { @@ -99,8 +103,8 @@ export const fooWowMutation = (options?: Partial>): Mutation export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -108,14 +112,14 @@ export const apiVVersionODataControllerCountOptions = (options?: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -123,8 +127,8 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options>): MutationOptions, Options> => { @@ -143,8 +147,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -152,8 +156,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): MutationOptions, Options> => { @@ -273,8 +277,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -282,8 +286,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -317,10 +321,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -335,8 +339,8 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options>): MutationOptions, Options> => { @@ -383,8 +387,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -392,8 +396,8 @@ export const callWithDefaultParametersOptions = (options?: Options>): MutationOptions, Options> => { @@ -440,8 +444,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -449,8 +453,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions, Options> => { @@ -483,8 +487,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -492,14 +496,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -507,14 +511,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions, DummyAResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -522,14 +526,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions, DummyBResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -537,14 +541,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -552,8 +556,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions, Options> => { @@ -586,8 +590,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -595,14 +599,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions, TypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -610,8 +614,8 @@ export const typesOptions = (options: Options) => queryOptions>): MutationOptions, Options> => { @@ -630,8 +634,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions, FileResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -639,14 +643,14 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions, ComplexTypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -654,14 +658,14 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions, MultipartResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -669,8 +673,8 @@ export const multipartResponseOptions = (options?: Options>): MutationOptions, Options> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/fetch/@tanstack/svelte-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/fetch/@tanstack/svelte-query.gen.ts index 7e81c37313..befa35b62f 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/fetch/@tanstack/svelte-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/fetch/@tanstack/svelte-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions, skipToken } from '@tanstack/svelte-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const exportOptions = (options?: Options) => queryOptions>): MutationOptions> => { @@ -98,8 +102,8 @@ export const fooWowMutation = (options?: Partial>): Mutation export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -107,14 +111,14 @@ export const apiVVersionODataControllerCountOptions = (options?: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -122,8 +126,8 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options>): MutationOptions> => { @@ -142,8 +146,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -151,8 +155,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): MutationOptions> => { @@ -272,8 +276,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -281,8 +285,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -316,10 +320,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -334,8 +338,8 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options>): MutationOptions> => { @@ -382,8 +386,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -391,8 +395,8 @@ export const callWithDefaultParametersOptions = (options?: Options>): MutationOptions> => { @@ -439,8 +443,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -448,8 +452,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions> => { @@ -482,8 +486,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -491,14 +495,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -506,14 +510,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -521,14 +525,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -536,14 +540,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -551,8 +555,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions> => { @@ -585,8 +589,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -594,14 +598,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -609,8 +613,8 @@ export const typesOptions = (options: Options) => queryOptions>): MutationOptions> => { @@ -629,8 +633,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -638,14 +642,14 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -653,14 +657,14 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -668,8 +672,8 @@ export const multipartResponseOptions = (options?: Options>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/name-builder/@tanstack/svelte-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/name-builder/@tanstack/svelte-query.gen.ts index 6a831b5b3e..ad8c29d041 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/name-builder/@tanstack/svelte-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/svelte-query/name-builder/@tanstack/svelte-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/svelte-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooD = (options?: Options) => createQueryKey('getFoo', options); -export const getFooE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooE = (options?: Options) => queryOptions>): MutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutC = (options?: Partial>): MutationOptions export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarE = (options?: Options) => queryOptions>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/asClass/@tanstack/vue-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/asClass/@tanstack/vue-query.gen.ts index 2e82ca3558..317e2a873f 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/asClass/@tanstack/vue-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/asClass/@tanstack/vue-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions } from '@tanstack/vue-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooOptions = (options?: Options) => queryOptions>): UseMutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutMutation = (options?: Partial>): UseMutat export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarOptions = (options?: Options) => queryOptio throwOnError: true }); return data; - }, - queryKey: getFooBarQueryKey(options) + }), + queryKey: getFooBarQueryKey(resolveOptions(options)) }); export const fooBarPostMutation = (options?: Partial>): UseMutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/axios/@tanstack/vue-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/axios/@tanstack/vue-query.gen.ts index f839621a3d..69b570cb63 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/axios/@tanstack/vue-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/axios/@tanstack/vue-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, skipToken, type UseMutationOptions } from '@tanstack/vue-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; @@ -40,10 +40,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -51,8 +55,8 @@ export const exportOptions = (options?: Options) => queryOptions>): UseMutationOptions, Options> => { @@ -99,8 +103,8 @@ export const fooWowMutation = (options?: Partial>): UseMutat export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -108,14 +112,14 @@ export const apiVVersionODataControllerCountOptions = (options?: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -123,8 +127,8 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options>): UseMutationOptions, Options> => { @@ -143,8 +147,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -152,8 +156,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): UseMutationOptions, Options> => { @@ -273,8 +277,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -282,8 +286,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -317,10 +321,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -335,8 +339,8 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options>): UseMutationOptions, Options> => { @@ -383,8 +387,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -392,8 +396,8 @@ export const callWithDefaultParametersOptions = (options?: Options>): UseMutationOptions, Options> => { @@ -440,8 +444,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -449,8 +453,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions, Options> => { @@ -483,8 +487,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -492,14 +496,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -507,14 +511,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions, DummyAResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -522,14 +526,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions, DummyBResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -537,14 +541,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -552,8 +556,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { @@ -586,8 +590,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -595,14 +599,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions, TypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -610,8 +614,8 @@ export const typesOptions = (options: Options) => queryOptions>): UseMutationOptions, Options> => { @@ -630,8 +634,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions, FileResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -639,14 +643,14 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions, ComplexTypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -654,14 +658,14 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions, MultipartResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -669,8 +673,8 @@ export const multipartResponseOptions = (options?: Options>): UseMutationOptions, Options> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/fetch/@tanstack/vue-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/fetch/@tanstack/vue-query.gen.ts index bbcab4d5a3..9caddbf556 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/fetch/@tanstack/vue-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/fetch/@tanstack/vue-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, skipToken, type UseMutationOptions } from '@tanstack/vue-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const exportOptions = (options?: Options) => queryOptions>): UseMutationOptions> => { @@ -98,8 +102,8 @@ export const fooWowMutation = (options?: Partial>): UseMutat export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -107,14 +111,14 @@ export const apiVVersionODataControllerCountOptions = (options?: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -122,8 +126,8 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options>): UseMutationOptions> => { @@ -142,8 +146,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -151,8 +155,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): UseMutationOptions> => { @@ -272,8 +276,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -281,8 +285,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -316,10 +320,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -334,8 +338,8 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options>): UseMutationOptions> => { @@ -382,8 +386,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -391,8 +395,8 @@ export const callWithDefaultParametersOptions = (options?: Options>): UseMutationOptions> => { @@ -439,8 +443,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -448,8 +452,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { @@ -482,8 +486,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -491,14 +495,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -506,14 +510,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -521,14 +525,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -536,14 +540,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -551,8 +555,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { @@ -585,8 +589,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -594,14 +598,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -609,8 +613,8 @@ export const typesOptions = (options: Options) => queryOptions>): UseMutationOptions> => { @@ -629,8 +633,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -638,14 +642,14 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -653,14 +657,14 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -668,8 +672,8 @@ export const multipartResponseOptions = (options?: Options>): UseMutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/name-builder/@tanstack/vue-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/name-builder/@tanstack/vue-query.gen.ts index bfd35f1d62..3c3f7038e9 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/name-builder/@tanstack/vue-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.0.x/plugins/@tanstack/vue-query/name-builder/@tanstack/vue-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions } from '@tanstack/vue-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooD = (options?: Options) => createQueryKey('getFoo', options); -export const getFooE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooE = (options?: Options) => queryOptions>): UseMutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutC = (options?: Partial>): UseMutationOpti export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarE = (options?: Options) => queryOptions>): UseMutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/internal-name-conflict/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/internal-name-conflict/@tanstack/react-query.gen.ts index c7e01dadfe..fd910359e7 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/internal-name-conflict/@tanstack/react-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/internal-name-conflict/@tanstack/react-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/react-query'; import { client } from '../client.gen'; import { create, create2, create3, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const createQueryKey2 = (options?: Options) => createQueryKey('create', options); -export const createOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const createOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await create({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const createOptions = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useCreateQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(createOptions, options); + export const create2Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pagination-ref/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pagination-ref/@tanstack/react-query.gen.ts index b9e75835bb..eaa592abdc 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pagination-ref/@tanstack/react-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/pagination-ref/@tanstack/react-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/react-query'; import { client } from '../client.gen'; import { getFoo, type Options, postFoo } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooOptions = (options: Options) => queryOptions[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -85,10 +89,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getFooInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getFoo', options, true); -export const getFooInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | null | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getFooInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, QueryKey>, number | null | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -103,10 +107,22 @@ export const getFooInfiniteOptions = (options: Options) => infiniteQ throwOnError: true }); return data; - }, - queryKey: getFooInfiniteQueryKey(options) + }), + queryKey: getFooInfiniteQueryKey(resolveOptions(options)) }); +const queryWithOptions = (optionsFn: (...args: Array) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useGetFooQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooOptions, options); + export const postFooMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/asClass/@tanstack/angular-query-experimental.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/asClass/@tanstack/angular-query-experimental.gen.ts index ac5127274b..46e0cb1551 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/asClass/@tanstack/angular-query-experimental.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/asClass/@tanstack/angular-query-experimental.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/angular-query-experimental'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooOptions = (options?: Options) => queryOptions>): MutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutMutation = (options?: Partial>): Mutation export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarOptions = (options?: Options) => queryOptio throwOnError: true }); return data; - }, - queryKey: getFooBarQueryKey(options) + }), + queryKey: getFooBarQueryKey(resolveOptions(options)) }); export const fooBarPostMutation = (options?: Partial>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/axios/@tanstack/angular-query-experimental.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/axios/@tanstack/angular-query-experimental.gen.ts index 5b07cde6a8..8a58ffade5 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/axios/@tanstack/angular-query-experimental.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/axios/@tanstack/angular-query-experimental.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions, skipToken } from '@tanstack/angular-query-experimental'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; @@ -40,10 +40,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -51,8 +55,8 @@ export const exportOptions = (options?: Options) => queryOptions>): MutationOptions, Options> => { @@ -99,8 +103,8 @@ export const fooWowMutation = (options?: Partial>): Mutation export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -108,14 +112,14 @@ export const apiVVersionODataControllerCountOptions = (options?: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -123,8 +127,8 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options>): MutationOptions, Options> => { @@ -143,8 +147,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -152,8 +156,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): MutationOptions, Options> => { @@ -273,8 +277,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -282,8 +286,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -317,10 +321,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -335,8 +339,8 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options>): MutationOptions, Options> => { @@ -383,8 +387,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -392,8 +396,8 @@ export const callWithDefaultParametersOptions = (options?: Options>): MutationOptions, Options> => { @@ -440,8 +444,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -449,8 +453,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions, Options> => { @@ -483,8 +487,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -492,14 +496,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -507,14 +511,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions, DummyAResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -522,14 +526,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions, DummyBResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -537,14 +541,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -552,8 +556,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions, Options> => { @@ -586,8 +590,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -595,14 +599,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions, TypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -610,8 +614,8 @@ export const typesOptions = (options: Options) => queryOptions>): MutationOptions, Options> => { @@ -630,8 +634,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions, FileResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -639,14 +643,14 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions, ComplexTypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -654,14 +658,14 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions, MultipartResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -669,8 +673,8 @@ export const multipartResponseOptions = (options?: Options>): MutationOptions, Options> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/fetch/@tanstack/angular-query-experimental.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/fetch/@tanstack/angular-query-experimental.gen.ts index 6cc80fb17d..d412e3ad70 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/fetch/@tanstack/angular-query-experimental.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/fetch/@tanstack/angular-query-experimental.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions, skipToken } from '@tanstack/angular-query-experimental'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const exportOptions = (options?: Options) => queryOptions>): MutationOptions> => { @@ -98,8 +102,8 @@ export const fooWowMutation = (options?: Partial>): Mutation export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -107,14 +111,14 @@ export const apiVVersionODataControllerCountOptions = (options?: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -122,8 +126,8 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options>): MutationOptions> => { @@ -142,8 +146,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -151,8 +155,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): MutationOptions> => { @@ -272,8 +276,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -281,8 +285,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -316,10 +320,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -334,8 +338,8 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options>): MutationOptions> => { @@ -382,8 +386,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -391,8 +395,8 @@ export const callWithDefaultParametersOptions = (options?: Options>): MutationOptions> => { @@ -439,8 +443,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -448,8 +452,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions> => { @@ -482,8 +486,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -491,14 +495,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -506,14 +510,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -521,14 +525,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -536,14 +540,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -551,8 +555,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions> => { @@ -585,8 +589,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -594,14 +598,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -609,8 +613,8 @@ export const typesOptions = (options: Options) => queryOptions>): MutationOptions> => { @@ -629,8 +633,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -638,14 +642,14 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -653,14 +657,14 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -668,8 +672,8 @@ export const multipartResponseOptions = (options?: Options>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/name-builder/@tanstack/angular-query-experimental.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/name-builder/@tanstack/angular-query-experimental.gen.ts index b144ed7a2c..14938efa33 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/name-builder/@tanstack/angular-query-experimental.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/angular-query-experimental/name-builder/@tanstack/angular-query-experimental.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/angular-query-experimental'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/angular-query-experimental'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooD = (options?: Options) => createQueryKey('getFoo', options); -export const getFooE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooE = (options?: Options) => queryOptions>): MutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutC = (options?: Partial>): MutationOptions export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarE = (options?: Options) => queryOptions>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/asClass/@tanstack/preact-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/asClass/@tanstack/preact-query.gen.ts index 92fa2c6b00..6e3235ff7f 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/asClass/@tanstack/preact-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/asClass/@tanstack/preact-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/preact-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const getFooOptions = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useGetFooQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooOptions, options); + export const fooPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -84,8 +100,8 @@ export const fooPutMutation = (options?: Partial>): UseMutat export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], @@ -93,10 +109,14 @@ export const getFooBarOptions = (options?: Options) => queryOptio throwOnError: true }); return data; - }, - queryKey: getFooBarQueryKey(options) + }), + queryKey: getFooBarQueryKey(resolveOptions(options)) }); +export const useGetFooBarQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooBarOptions, options); + export const fooBarPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/axios/@tanstack/preact-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/axios/@tanstack/preact-query.gen.ts index 586296750d..2c620a72f3 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/axios/@tanstack/preact-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/axios/@tanstack/preact-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/preact-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; @@ -40,10 +40,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -51,10 +55,22 @@ export const exportOptions = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useExportQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(exportOptions, options); + export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -99,8 +115,8 @@ export const fooWowMutation = (options?: Partial>): UseMutat export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -108,14 +124,18 @@ export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(apiVVersionODataControllerCountOptions, options); + export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -123,10 +143,14 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getApiVbyApiVersionSimpleOperationOptions, options); + export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -143,8 +167,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -152,10 +176,14 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithoutParametersAndResponseOptions, options); + export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -273,8 +301,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -282,8 +310,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -317,10 +345,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -335,10 +363,14 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithOptionalParamOptions, options); + export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -383,8 +415,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -392,10 +424,14 @@ export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithDefaultParametersOptions, options); + export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -440,8 +476,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -449,10 +485,14 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); +export const useDuplicateName2Query = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(duplicateName2Options, options); + export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -483,8 +523,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -492,14 +532,18 @@ export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithNoContentResponseOptions, options); + export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -507,14 +551,18 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseAndNoContentResponseOptions, options); + export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions, DummyAResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -522,14 +570,18 @@ export const dummyAOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyAOptions, options); + export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions, DummyBResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -537,14 +589,18 @@ export const dummyBOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyBOptions, options); + export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -552,10 +608,14 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); +export const useCallWithResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseOptions, options); + export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -586,8 +646,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -595,14 +655,18 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); +export const useCollectionFormatQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(collectionFormatOptions, options); + export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions, TypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -610,10 +674,14 @@ export const typesOptions = (options: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(typesOptions, options); + export const uploadFileMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -630,8 +698,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions, FileResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -639,14 +707,18 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); +export const useFileResponseQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(fileResponseOptions, options); + export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions, ComplexTypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -654,14 +726,18 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); +export const useComplexTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(complexTypesOptions, options); + export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions, MultipartResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -669,10 +745,14 @@ export const multipartResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(multipartResponseOptions, options); + export const multipartRequestMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/fetch/@tanstack/preact-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/fetch/@tanstack/preact-query.gen.ts index 33d1fb83e9..408924a08c 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/fetch/@tanstack/preact-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/fetch/@tanstack/preact-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/preact-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const exportOptions = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useExportQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(exportOptions, options); + export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -98,8 +114,8 @@ export const fooWowMutation = (options?: Partial>): UseMutat export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -107,14 +123,18 @@ export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(apiVVersionODataControllerCountOptions, options); + export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -122,10 +142,14 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getApiVbyApiVersionSimpleOperationOptions, options); + export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -142,8 +166,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -151,10 +175,14 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithoutParametersAndResponseOptions, options); + export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -272,8 +300,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -281,8 +309,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -316,10 +344,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -334,10 +362,14 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithOptionalParamOptions, options); + export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -382,8 +414,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -391,10 +423,14 @@ export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithDefaultParametersOptions, options); + export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -439,8 +475,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -448,10 +484,14 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); +export const useDuplicateName2Query = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(duplicateName2Options, options); + export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -482,8 +522,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -491,14 +531,18 @@ export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithNoContentResponseOptions, options); + export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -506,14 +550,18 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseAndNoContentResponseOptions, options); + export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -521,14 +569,18 @@ export const dummyAOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyAOptions, options); + export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -536,14 +588,18 @@ export const dummyBOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyBOptions, options); + export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -551,10 +607,14 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); +export const useCallWithResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseOptions, options); + export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -585,8 +645,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -594,14 +654,18 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); +export const useCollectionFormatQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(collectionFormatOptions, options); + export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -609,10 +673,14 @@ export const typesOptions = (options: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(typesOptions, options); + export const uploadFileMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -629,8 +697,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -638,14 +706,18 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); +export const useFileResponseQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(fileResponseOptions, options); + export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -653,14 +725,18 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); +export const useComplexTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(complexTypesOptions, options); + export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -668,10 +744,14 @@ export const multipartResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(multipartResponseOptions, options); + export const multipartRequestMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/name-builder/@tanstack/preact-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/name-builder/@tanstack/preact-query.gen.ts index 5552d69766..a363fc4b56 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/name-builder/@tanstack/preact-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/preact-query/name-builder/@tanstack/preact-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/preact-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/preact-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooD = (options?: Options) => createQueryKey('getFoo', options); -export const getFooE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const getFooE = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useGetFooQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooE, options); + export const fooPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -84,8 +100,8 @@ export const fooPutC = (options?: Partial>): UseMutationOpti export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], @@ -93,10 +109,14 @@ export const getFooBarE = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooBarE, options); + export const fooBarPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/asClass/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/asClass/@tanstack/react-query.gen.ts index 486657ead7..acd235e3f0 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/asClass/@tanstack/react-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/asClass/@tanstack/react-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/react-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const getFooOptions = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useGetFooQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooOptions, options); + export const fooPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -84,8 +100,8 @@ export const fooPutMutation = (options?: Partial>): UseMutat export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], @@ -93,10 +109,14 @@ export const getFooBarOptions = (options?: Options) => queryOptio throwOnError: true }); return data; - }, - queryKey: getFooBarQueryKey(options) + }), + queryKey: getFooBarQueryKey(resolveOptions(options)) }); +export const useGetFooBarQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooBarOptions, options); + export const fooBarPostMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/axios/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/axios/@tanstack/react-query.gen.ts index 38403265b8..7f34770259 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/axios/@tanstack/react-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/axios/@tanstack/react-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/react-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; @@ -40,10 +40,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -51,10 +55,22 @@ export const exportOptions = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useExportQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(exportOptions, options); + export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -99,8 +115,8 @@ export const fooWowMutation = (options?: Partial>): UseMutat export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -108,14 +124,18 @@ export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(apiVVersionODataControllerCountOptions, options); + export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -123,10 +143,14 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getApiVbyApiVersionSimpleOperationOptions, options); + export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -143,8 +167,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -152,10 +176,14 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithoutParametersAndResponseOptions, options); + export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -273,8 +301,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -282,8 +310,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -317,10 +345,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -335,10 +363,14 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithOptionalParamOptions, options); + export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -383,8 +415,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -392,10 +424,14 @@ export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithDefaultParametersOptions, options); + export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -440,8 +476,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -449,10 +485,14 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); +export const useDuplicateName2Query = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(duplicateName2Options, options); + export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -483,8 +523,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -492,14 +532,18 @@ export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithNoContentResponseOptions, options); + export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -507,14 +551,18 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseAndNoContentResponseOptions, options); + export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions, DummyAResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -522,14 +570,18 @@ export const dummyAOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyAOptions, options); + export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions, DummyBResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -537,14 +589,18 @@ export const dummyBOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyBOptions, options); + export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -552,10 +608,14 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); +export const useCallWithResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseOptions, options); + export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -586,8 +646,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -595,14 +655,18 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); +export const useCollectionFormatQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(collectionFormatOptions, options); + export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions, TypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -610,10 +674,14 @@ export const typesOptions = (options: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(typesOptions, options); + export const uploadFileMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { @@ -630,8 +698,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions, FileResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -639,14 +707,18 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); +export const useFileResponseQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(fileResponseOptions, options); + export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions, ComplexTypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -654,14 +726,18 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); +export const useComplexTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(complexTypesOptions, options); + export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions, MultipartResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -669,10 +745,14 @@ export const multipartResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(multipartResponseOptions, options); + export const multipartRequestMutation = (options?: Partial>): UseMutationOptions, Options> => { const mutationOptions: UseMutationOptions, Options> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/fetch/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/fetch/@tanstack/react-query.gen.ts index 378082bd09..b942d5c500 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/fetch/@tanstack/react-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/fetch/@tanstack/react-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/react-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const exportOptions = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useExportQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(exportOptions, options); + export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -98,8 +114,8 @@ export const fooWowMutation = (options?: Partial>): UseMutat export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -107,14 +123,18 @@ export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(apiVVersionODataControllerCountOptions, options); + export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -122,10 +142,14 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getApiVbyApiVersionSimpleOperationOptions, options); + export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -142,8 +166,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -151,10 +175,14 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithoutParametersAndResponseOptions, options); + export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -272,8 +300,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -281,8 +309,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -316,10 +344,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -334,10 +362,14 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithOptionalParamOptions, options); + export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -382,8 +414,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -391,10 +423,14 @@ export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithDefaultParametersOptions, options); + export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -439,8 +475,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -448,10 +484,14 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); +export const useDuplicateName2Query = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(duplicateName2Options, options); + export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -482,8 +522,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -491,14 +531,18 @@ export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithNoContentResponseOptions, options); + export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -506,14 +550,18 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseAndNoContentResponseOptions, options); + export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -521,14 +569,18 @@ export const dummyAOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyAOptions, options); + export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -536,14 +588,18 @@ export const dummyBOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyBOptions, options); + export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -551,10 +607,14 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); +export const useCallWithResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseOptions, options); + export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -585,8 +645,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -594,14 +654,18 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); +export const useCollectionFormatQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(collectionFormatOptions, options); + export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -609,10 +673,14 @@ export const typesOptions = (options: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(typesOptions, options); + export const uploadFileMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -629,8 +697,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -638,14 +706,18 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); +export const useFileResponseQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(fileResponseOptions, options); + export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -653,14 +725,18 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); +export const useComplexTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(complexTypesOptions, options); + export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -668,10 +744,14 @@ export const multipartResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(multipartResponseOptions, options); + export const multipartRequestMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/name-builder/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/name-builder/@tanstack/react-query.gen.ts index 43c90277c2..34df178948 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/name-builder/@tanstack/react-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/name-builder/@tanstack/react-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/react-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooD = (options?: Options) => createQueryKey('getFoo', options); -export const getFooE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const getFooE = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useGetFooQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooE, options); + export const fooPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -84,8 +100,8 @@ export const fooPutC = (options?: Partial>): UseMutationOpti export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], @@ -93,10 +109,14 @@ export const getFooBarE = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getFooBarE, options); + export const fooBarPostC = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/@tanstack/react-query.gen.ts new file mode 100644 index 0000000000..40c8901183 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/@tanstack/react-query.gen.ts @@ -0,0 +1,840 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/react-query'; + +import { client } from '../client.gen'; +import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; +import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; + +export type QueryKey = [ + Pick & { + _id: string; + _infinite?: boolean; + tags?: ReadonlyArray; + } +]; + +const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ + QueryKey[0] +] => { + const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; + if (infinite) { + params._infinite = infinite; + } + if (tags) { + params.tags = tags; + } + if (options?.body) { + params.body = options.body; + } + if (options?.headers) { + params.headers = options.headers; + } + if (options?.path) { + params.path = options.path; + } + if (options?.query) { + params.query = options.query; + } + return [params]; +}; + +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + +export const exportQueryKey = (options?: Options) => createQueryKey('export', options); + +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await export_({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: exportQueryKey(resolveOptions(options)) +}); + +const queryWithOptions = (optionsFn: Function, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useExportQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(exportOptions, options); + +export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await patchApiVbyApiVersionNoTag({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const importMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await import_({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const fooWowMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await fooWow({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); + +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await apiVVersionODataControllerCount({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: apiVVersionODataControllerCountQueryKey(resolveOptions(options)) +}); + +export const useApiVVersionODataControllerCountQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(apiVVersionODataControllerCountOptions, options); + +export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); + +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await getApiVbyApiVersionSimpleOperation({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: getApiVbyApiVersionSimpleOperationQueryKey(resolveOptions(options)) +}); + +export const useGetApiVbyApiVersionSimpleOperationQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getApiVbyApiVersionSimpleOperationOptions, options); + +export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deleteCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); + +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await getCallWithoutParametersAndResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: getCallWithoutParametersAndResponseQueryKey(resolveOptions(options)) +}); + +export const useGetCallWithoutParametersAndResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithoutParametersAndResponseOptions, options); + +export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await patchCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await putCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const deleteFooMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deleteFoo({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDescriptions({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * @deprecated + */ +export const deprecatedCallMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deprecatedCall({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithParametersMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithParameters({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithWeirdParameterNames({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); + +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await getCallWithOptionalParam({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: getCallWithOptionalParamQueryKey(resolveOptions(options)) +}); + +const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { + const params = { ...queryKey[0] }; + if (page.body) { + params.body = { + ...queryKey[0].body as any, + ...page.body as any + }; + } + if (page.headers) { + params.headers = { + ...queryKey[0].headers, + ...page.headers + }; + } + if (page.path) { + params.path = { + ...queryKey[0].path as any, + ...page.path as any + }; + } + if (page.query) { + params.query = { + ...queryKey[0].query as any, + ...page.query as any + }; + } + return params as unknown as typeof page; +}; + +export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); + +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +// @ts-ignore +{ + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { + // @ts-ignore + const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { + query: { + page: pageParam + } + }; + const params = createInfiniteParams(queryKey, page); + const { data } = await getCallWithOptionalParam({ + ...options, + ...params, + signal, + throwOnError: true + }); + return data; + }), + queryKey: getCallWithOptionalParamInfiniteQueryKey(resolveOptions(options)) +}); + +export const useGetCallWithOptionalParamQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithOptionalParamOptions, options); + +export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postCallWithOptionalParam({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postApiVbyApiVersionRequestBody({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postApiVbyApiVersionFormData({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); + +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithDefaultParameters({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithDefaultParametersQueryKey(resolveOptions(options)) +}); + +export const useCallWithDefaultParametersQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithDefaultParametersOptions, options); + +export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDefaultOptionalParameters({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callToTestOrderOfParams({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateNameMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); + +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await duplicateName2({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) +}); + +export const useDuplicateName2Query = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(duplicateName2Options, options); + +export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName3({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName4({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); + +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithNoContentResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithNoContentResponseQueryKey(resolveOptions(options)) +}); + +export const useCallWithNoContentResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithNoContentResponseOptions, options); + +export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); + +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithResponseAndNoContentResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithResponseAndNoContentResponseQueryKey(resolveOptions(options)) +}); + +export const useCallWithResponseAndNoContentResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseAndNoContentResponseOptions, options); + +export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); + +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await dummyA({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: dummyAQueryKey(resolveOptions(options)) +}); + +export const useDummyAQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyAOptions, options); + +export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); + +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await dummyB({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: dummyBQueryKey(resolveOptions(options)) +}); + +export const useDummyBQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyBOptions, options); + +export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); + +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) +}); + +export const useCallWithResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseOptions, options); + +export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDuplicateResponses({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithResponses({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); + +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await collectionFormat({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) +}); + +export const useCollectionFormatQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(collectionFormatOptions, options); + +export const typesQueryKey = (options: Options) => createQueryKey('types', options); + +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await types({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: typesQueryKey(resolveOptions(options)) +}); + +export const useTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(typesOptions, options); + +export const uploadFileMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await uploadFile({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); + +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await fileResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) +}); + +export const useFileResponseQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(fileResponseOptions, options); + +export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); + +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await complexTypes({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) +}); + +export const useComplexTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(complexTypesOptions, options); + +export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); + +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await multipartResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: multipartResponseQueryKey(resolveOptions(options)) +}); + +export const useMultipartResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(multipartResponseOptions, options); + +export const multipartRequestMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await multipartRequest({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const complexParamsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await complexParams({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithResultFromHeader({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await testErrorCode({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * Login User + */ +export const putWithFormUrlEncodedMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await putWithFormUrlEncoded({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/client.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/client.gen.ts new file mode 100644 index 0000000000..25cd14eafb --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/client.gen.ts @@ -0,0 +1,16 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type ClientOptions, type Config, createClient, createConfig } from './client'; +import type { ClientOptions as ClientOptions2 } from './types.gen'; + +/** + * The `createClientConfig()` function will be called on client initialization + * and the returned object will become the client's initial configuration. + * + * You may want to initialize your client this way instead of calling + * `setConfig()`. This is useful for example if you're using Next.js + * to ensure your client always has the correct values. + */ +export type CreateClientConfig = (override?: Config) => Config & T>; + +export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/client/client.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/client/client.gen.ts new file mode 100644 index 0000000000..14dc0a0ec5 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/client/client.gen.ts @@ -0,0 +1,290 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { createSseClient } from '../core/serverSentEvents.gen'; +import type { HttpMethod } from '../core/types.gen'; +import { getValidRequestBody } from '../core/utils.gen'; +import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; +import { + buildUrl, + createConfig, + createInterceptors, + getParseAs, + mergeConfigs, + mergeHeaders, + setAuthParams, +} from './utils.gen'; + +type ReqInit = Omit & { + body?: any; + headers: ReturnType; +}; + +export const createClient = (config: Config = {}): Client => { + let _config = mergeConfigs(createConfig(), config); + + const getConfig = (): Config => ({ ..._config }); + + const setConfig = (config: Config): Config => { + _config = mergeConfigs(_config, config); + return getConfig(); + }; + + const interceptors = createInterceptors(); + + const beforeRequest = async (options: RequestOptions) => { + const opts = { + ..._config, + ...options, + fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, + headers: mergeHeaders(_config.headers, options.headers), + serializedBody: undefined as string | undefined, + }; + + if (opts.security) { + await setAuthParams({ + ...opts, + security: opts.security, + }); + } + + if (opts.requestValidator) { + await opts.requestValidator(opts); + } + + if (opts.body !== undefined && opts.bodySerializer) { + opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; + } + + // remove Content-Type header if body is empty to avoid sending invalid requests + if (opts.body === undefined || opts.serializedBody === '') { + opts.headers.delete('Content-Type'); + } + + const url = buildUrl(opts); + + return { opts, url }; + }; + + const request: Client['request'] = async (options) => { + // @ts-expect-error + const { opts, url } = await beforeRequest(options); + const requestInit: ReqInit = { + redirect: 'follow', + ...opts, + body: getValidRequestBody(opts), + }; + + let request = new Request(url, requestInit); + + for (const fn of interceptors.request.fns) { + if (fn) { + request = await fn(request, opts); + } + } + + // fetch must be assigned here, otherwise it would throw the error: + // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation + const _fetch = opts.fetch!; + let response: Response; + + try { + response = await _fetch(request); + } catch (error) { + // Handle fetch exceptions (AbortError, network errors, etc.) + let finalError = error; + + for (const fn of interceptors.error.fns) { + if (fn) { + finalError = (await fn(error, undefined as any, request, opts)) as unknown; + } + } + + finalError = finalError || ({} as unknown); + + if (opts.throwOnError) { + throw finalError; + } + + // Return error response + return opts.responseStyle === 'data' + ? undefined + : { + error: finalError, + request, + response: undefined as any, + }; + } + + for (const fn of interceptors.response.fns) { + if (fn) { + response = await fn(response, request, opts); + } + } + + const result = { + request, + response, + }; + + if (response.ok) { + const parseAs = + (opts.parseAs === 'auto' + ? getParseAs(response.headers.get('Content-Type')) + : opts.parseAs) ?? 'json'; + + if (response.status === 204 || response.headers.get('Content-Length') === '0') { + let emptyData: any; + switch (parseAs) { + case 'arrayBuffer': + case 'blob': + case 'text': + emptyData = await response[parseAs](); + break; + case 'formData': + emptyData = new FormData(); + break; + case 'stream': + emptyData = response.body; + break; + case 'json': + default: + emptyData = {}; + break; + } + return opts.responseStyle === 'data' + ? emptyData + : { + data: emptyData, + ...result, + }; + } + + let data: any; + switch (parseAs) { + case 'arrayBuffer': + case 'blob': + case 'formData': + case 'text': + data = await response[parseAs](); + break; + case 'json': { + // Some servers return 200 with no Content-Length and empty body. + // response.json() would throw; read as text and parse if non-empty. + const text = await response.text(); + data = text ? JSON.parse(text) : {}; + break; + } + case 'stream': + return opts.responseStyle === 'data' + ? response.body + : { + data: response.body, + ...result, + }; + } + + if (parseAs === 'json') { + if (opts.responseValidator) { + await opts.responseValidator(data); + } + + if (opts.responseTransformer) { + data = await opts.responseTransformer(data); + } + } + + return opts.responseStyle === 'data' + ? data + : { + data, + ...result, + }; + } + + const textError = await response.text(); + let jsonError: unknown; + + try { + jsonError = JSON.parse(textError); + } catch { + // noop + } + + const error = jsonError ?? textError; + let finalError = error; + + for (const fn of interceptors.error.fns) { + if (fn) { + finalError = (await fn(error, response, request, opts)) as string; + } + } + + finalError = finalError || ({} as string); + + if (opts.throwOnError) { + throw finalError; + } + + // TODO: we probably want to return error and improve types + return opts.responseStyle === 'data' + ? undefined + : { + error: finalError, + ...result, + }; + }; + + const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => + request({ ...options, method }); + + const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { + const { opts, url } = await beforeRequest(options); + return createSseClient({ + ...opts, + body: opts.body as BodyInit | null | undefined, + headers: opts.headers as unknown as Record, + method, + onRequest: async (url, init) => { + let request = new Request(url, init); + for (const fn of interceptors.request.fns) { + if (fn) { + request = await fn(request, opts); + } + } + return request; + }, + serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, + url, + }); + }; + + const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); + + return { + buildUrl: _buildUrl, + connect: makeMethodFn('CONNECT'), + delete: makeMethodFn('DELETE'), + get: makeMethodFn('GET'), + getConfig, + head: makeMethodFn('HEAD'), + interceptors, + options: makeMethodFn('OPTIONS'), + patch: makeMethodFn('PATCH'), + post: makeMethodFn('POST'), + put: makeMethodFn('PUT'), + request, + setConfig, + sse: { + connect: makeSseFn('CONNECT'), + delete: makeSseFn('DELETE'), + get: makeSseFn('GET'), + head: makeSseFn('HEAD'), + options: makeSseFn('OPTIONS'), + patch: makeSseFn('PATCH'), + post: makeSseFn('POST'), + put: makeSseFn('PUT'), + trace: makeSseFn('TRACE'), + }, + trace: makeMethodFn('TRACE'), + } as Client; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/client/index.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/client/index.ts new file mode 100644 index 0000000000..b295edeca0 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/client/index.ts @@ -0,0 +1,25 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type { Auth } from '../core/auth.gen'; +export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; +export { + formDataBodySerializer, + jsonBodySerializer, + urlSearchParamsBodySerializer, +} from '../core/bodySerializer.gen'; +export { buildClientParams } from '../core/params.gen'; +export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; +export { createClient } from './client.gen'; +export type { + Client, + ClientOptions, + Config, + CreateClientConfig, + Options, + RequestOptions, + RequestResult, + ResolvedRequestOptions, + ResponseStyle, + TDataShape, +} from './types.gen'; +export { createConfig, mergeHeaders } from './utils.gen'; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/client/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/client/types.gen.ts new file mode 100644 index 0000000000..a3f8616511 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/client/types.gen.ts @@ -0,0 +1,214 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Auth } from '../core/auth.gen'; +import type { + ServerSentEventsOptions, + ServerSentEventsResult, +} from '../core/serverSentEvents.gen'; +import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; +import type { Middleware } from './utils.gen'; + +export type ResponseStyle = 'data' | 'fields'; + +export interface Config + extends Omit, CoreConfig { + /** + * Base URL for all requests made by this client. + */ + baseUrl?: T['baseUrl']; + /** + * Fetch API implementation. You can use this option to provide a custom + * fetch instance. + * + * @default globalThis.fetch + */ + fetch?: typeof fetch; + /** + * Please don't use the Fetch client for Next.js applications. The `next` + * options won't have any effect. + * + * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. + */ + next?: never; + /** + * Return the response data parsed in a specified format. By default, `auto` + * will infer the appropriate method from the `Content-Type` response header. + * You can override this behavior with any of the {@link Body} methods. + * Select `stream` if you don't want to parse response data at all. + * + * @default 'auto' + */ + parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; + /** + * Should we return only data or multiple fields (data, error, response, etc.)? + * + * @default 'fields' + */ + responseStyle?: ResponseStyle; + /** + * Throw an error instead of returning it in the response? + * + * @default false + */ + throwOnError?: T['throwOnError']; +} + +export interface RequestOptions< + TData = unknown, + TResponseStyle extends ResponseStyle = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, +> + extends + Config<{ + responseStyle: TResponseStyle; + throwOnError: ThrowOnError; + }>, + Pick< + ServerSentEventsOptions, + | 'onRequest' + | 'onSseError' + | 'onSseEvent' + | 'sseDefaultRetryDelay' + | 'sseMaxRetryAttempts' + | 'sseMaxRetryDelay' + > { + /** + * Any body that you want to add to your request. + * + * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} + */ + body?: unknown; + path?: Record; + query?: Record; + /** + * Security mechanism(s) to use for the request. + */ + security?: ReadonlyArray; + url: Url; +} + +export interface ResolvedRequestOptions< + TResponseStyle extends ResponseStyle = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, +> extends RequestOptions { + serializedBody?: string; +} + +export type RequestResult< + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = boolean, + TResponseStyle extends ResponseStyle = 'fields', +> = ThrowOnError extends true + ? Promise< + TResponseStyle extends 'data' + ? TData extends Record + ? TData[keyof TData] + : TData + : { + data: TData extends Record ? TData[keyof TData] : TData; + request: Request; + response: Response; + } + > + : Promise< + TResponseStyle extends 'data' + ? (TData extends Record ? TData[keyof TData] : TData) | undefined + : ( + | { + data: TData extends Record ? TData[keyof TData] : TData; + error: undefined; + } + | { + data: undefined; + error: TError extends Record ? TError[keyof TError] : TError; + } + ) & { + request: Request; + response: Response; + } + >; + +export interface ClientOptions { + baseUrl?: string; + responseStyle?: ResponseStyle; + throwOnError?: boolean; +} + +type MethodFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'>, +) => RequestResult; + +type SseFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'>, +) => Promise>; + +type RequestFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'> & + Pick>, 'method'>, +) => RequestResult; + +type BuildUrlFn = < + TData extends { + body?: unknown; + path?: Record; + query?: Record; + url: string; + }, +>( + options: TData & Options, +) => string; + +export type Client = CoreClient & { + interceptors: Middleware; +}; + +/** + * The `createClientConfig()` function will be called on client initialization + * and the returned object will become the client's initial configuration. + * + * You may want to initialize your client this way instead of calling + * `setConfig()`. This is useful for example if you're using Next.js + * to ensure your client always has the correct values. + */ +export type CreateClientConfig = ( + override?: Config, +) => Config & T>; + +export interface TDataShape { + body?: unknown; + headers?: unknown; + path?: unknown; + query?: unknown; + url: string; +} + +type OmitKeys = Pick>; + +export type Options< + TData extends TDataShape = TDataShape, + ThrowOnError extends boolean = boolean, + TResponse = unknown, + TResponseStyle extends ResponseStyle = 'fields', +> = OmitKeys< + RequestOptions, + 'body' | 'path' | 'query' | 'url' +> & + ([TData] extends [never] ? unknown : Omit); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/client/utils.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/client/utils.gen.ts new file mode 100644 index 0000000000..b4bd2435ce --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/client/utils.gen.ts @@ -0,0 +1,316 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { getAuthToken } from '../core/auth.gen'; +import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; +import { jsonBodySerializer } from '../core/bodySerializer.gen'; +import { + serializeArrayParam, + serializeObjectParam, + serializePrimitiveParam, +} from '../core/pathSerializer.gen'; +import { getUrl } from '../core/utils.gen'; +import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; + +export const createQuerySerializer = ({ + parameters = {}, + ...args +}: QuerySerializerOptions = {}) => { + const querySerializer = (queryParams: T) => { + const search: string[] = []; + if (queryParams && typeof queryParams === 'object') { + for (const name in queryParams) { + const value = queryParams[name]; + + if (value === undefined || value === null) { + continue; + } + + const options = parameters[name] || args; + + if (Array.isArray(value)) { + const serializedArray = serializeArrayParam({ + allowReserved: options.allowReserved, + explode: true, + name, + style: 'form', + value, + ...options.array, + }); + if (serializedArray) search.push(serializedArray); + } else if (typeof value === 'object') { + const serializedObject = serializeObjectParam({ + allowReserved: options.allowReserved, + explode: true, + name, + style: 'deepObject', + value: value as Record, + ...options.object, + }); + if (serializedObject) search.push(serializedObject); + } else { + const serializedPrimitive = serializePrimitiveParam({ + allowReserved: options.allowReserved, + name, + value: value as string, + }); + if (serializedPrimitive) search.push(serializedPrimitive); + } + } + } + return search.join('&'); + }; + return querySerializer; +}; + +/** + * Infers parseAs value from provided Content-Type header. + */ +export const getParseAs = (contentType: string | null): Exclude => { + if (!contentType) { + // If no Content-Type header is provided, the best we can do is return the raw response body, + // which is effectively the same as the 'stream' option. + return 'stream'; + } + + const cleanContent = contentType.split(';')[0]?.trim(); + + if (!cleanContent) { + return; + } + + if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { + return 'json'; + } + + if (cleanContent === 'multipart/form-data') { + return 'formData'; + } + + if ( + ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) + ) { + return 'blob'; + } + + if (cleanContent.startsWith('text/')) { + return 'text'; + } + + return; +}; + +const checkForExistence = ( + options: Pick & { + headers: Headers; + }, + name?: string, +): boolean => { + if (!name) { + return false; + } + if ( + options.headers.has(name) || + options.query?.[name] || + options.headers.get('Cookie')?.includes(`${name}=`) + ) { + return true; + } + return false; +}; + +export const setAuthParams = async ({ + security, + ...options +}: Pick, 'security'> & + Pick & { + headers: Headers; + }) => { + for (const auth of security) { + if (checkForExistence(options, auth.name)) { + continue; + } + + const token = await getAuthToken(auth, options.auth); + + if (!token) { + continue; + } + + const name = auth.name ?? 'Authorization'; + + switch (auth.in) { + case 'query': + if (!options.query) { + options.query = {}; + } + options.query[name] = token; + break; + case 'cookie': + options.headers.append('Cookie', `${name}=${token}`); + break; + case 'header': + default: + options.headers.set(name, token); + break; + } + } +}; + +export const buildUrl: Client['buildUrl'] = (options) => + getUrl({ + baseUrl: options.baseUrl as string, + path: options.path, + query: options.query, + querySerializer: + typeof options.querySerializer === 'function' + ? options.querySerializer + : createQuerySerializer(options.querySerializer), + url: options.url, + }); + +export const mergeConfigs = (a: Config, b: Config): Config => { + const config = { ...a, ...b }; + if (config.baseUrl?.endsWith('/')) { + config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); + } + config.headers = mergeHeaders(a.headers, b.headers); + return config; +}; + +const headersEntries = (headers: Headers): Array<[string, string]> => { + const entries: Array<[string, string]> = []; + headers.forEach((value, key) => { + entries.push([key, value]); + }); + return entries; +}; + +export const mergeHeaders = ( + ...headers: Array['headers'] | undefined> +): Headers => { + const mergedHeaders = new Headers(); + for (const header of headers) { + if (!header) { + continue; + } + + const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); + + for (const [key, value] of iterator) { + if (value === null) { + mergedHeaders.delete(key); + } else if (Array.isArray(value)) { + for (const v of value) { + mergedHeaders.append(key, v as string); + } + } else if (value !== undefined) { + // assume object headers are meant to be JSON stringified, i.e. their + // content value in OpenAPI specification is 'application/json' + mergedHeaders.set( + key, + typeof value === 'object' ? JSON.stringify(value) : (value as string), + ); + } + } + } + return mergedHeaders; +}; + +type ErrInterceptor = ( + error: Err, + response: Res, + request: Req, + options: Options, +) => Err | Promise; + +type ReqInterceptor = (request: Req, options: Options) => Req | Promise; + +type ResInterceptor = ( + response: Res, + request: Req, + options: Options, +) => Res | Promise; + +class Interceptors { + fns: Array = []; + + clear(): void { + this.fns = []; + } + + eject(id: number | Interceptor): void { + const index = this.getInterceptorIndex(id); + if (this.fns[index]) { + this.fns[index] = null; + } + } + + exists(id: number | Interceptor): boolean { + const index = this.getInterceptorIndex(id); + return Boolean(this.fns[index]); + } + + getInterceptorIndex(id: number | Interceptor): number { + if (typeof id === 'number') { + return this.fns[id] ? id : -1; + } + return this.fns.indexOf(id); + } + + update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { + const index = this.getInterceptorIndex(id); + if (this.fns[index]) { + this.fns[index] = fn; + return id; + } + return false; + } + + use(fn: Interceptor): number { + this.fns.push(fn); + return this.fns.length - 1; + } +} + +export interface Middleware { + error: Interceptors>; + request: Interceptors>; + response: Interceptors>; +} + +export const createInterceptors = (): Middleware< + Req, + Res, + Err, + Options +> => ({ + error: new Interceptors>(), + request: new Interceptors>(), + response: new Interceptors>(), +}); + +const defaultQuerySerializer = createQuerySerializer({ + allowReserved: false, + array: { + explode: true, + style: 'form', + }, + object: { + explode: true, + style: 'deepObject', + }, +}); + +const defaultHeaders = { + 'Content-Type': 'application/json', +}; + +export const createConfig = ( + override: Config & T> = {}, +): Config & T> => ({ + ...jsonBodySerializer, + headers: defaultHeaders, + parseAs: 'auto', + querySerializer: defaultQuerySerializer, + ...override, +}); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/auth.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/auth.gen.ts new file mode 100644 index 0000000000..3ebf994788 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/auth.gen.ts @@ -0,0 +1,41 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type AuthToken = string | undefined; + +export interface Auth { + /** + * Which part of the request do we use to send the auth? + * + * @default 'header' + */ + in?: 'header' | 'query' | 'cookie'; + /** + * Header or query parameter name. + * + * @default 'Authorization' + */ + name?: string; + scheme?: 'basic' | 'bearer'; + type: 'apiKey' | 'http'; +} + +export const getAuthToken = async ( + auth: Auth, + callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, +): Promise => { + const token = typeof callback === 'function' ? await callback(auth) : callback; + + if (!token) { + return; + } + + if (auth.scheme === 'bearer') { + return `Bearer ${token}`; + } + + if (auth.scheme === 'basic') { + return `Basic ${btoa(token)}`; + } + + return token; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/bodySerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/bodySerializer.gen.ts new file mode 100644 index 0000000000..67daca60f8 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/bodySerializer.gen.ts @@ -0,0 +1,82 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; + +export type QuerySerializer = (query: Record) => string; + +export type BodySerializer = (body: unknown) => unknown; + +type QuerySerializerOptionsObject = { + allowReserved?: boolean; + array?: Partial>; + object?: Partial>; +}; + +export type QuerySerializerOptions = QuerySerializerOptionsObject & { + /** + * Per-parameter serialization overrides. When provided, these settings + * override the global array/object settings for specific parameter names. + */ + parameters?: Record; +}; + +const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { + if (typeof value === 'string' || value instanceof Blob) { + data.append(key, value); + } else if (value instanceof Date) { + data.append(key, value.toISOString()); + } else { + data.append(key, JSON.stringify(value)); + } +}; + +const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { + if (typeof value === 'string') { + data.append(key, value); + } else { + data.append(key, JSON.stringify(value)); + } +}; + +export const formDataBodySerializer = { + bodySerializer: (body: unknown): FormData => { + const data = new FormData(); + + Object.entries(body as Record).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + if (Array.isArray(value)) { + value.forEach((v) => serializeFormDataPair(data, key, v)); + } else { + serializeFormDataPair(data, key, value); + } + }); + + return data; + }, +}; + +export const jsonBodySerializer = { + bodySerializer: (body: unknown): string => + JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), +}; + +export const urlSearchParamsBodySerializer = { + bodySerializer: (body: unknown): string => { + const data = new URLSearchParams(); + + Object.entries(body as Record).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + if (Array.isArray(value)) { + value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); + } else { + serializeUrlSearchParamsPair(data, key, value); + } + }); + + return data.toString(); + }, +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/params.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/params.gen.ts new file mode 100644 index 0000000000..7955601a5c --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/params.gen.ts @@ -0,0 +1,169 @@ +// This file is auto-generated by @hey-api/openapi-ts + +type Slot = 'body' | 'headers' | 'path' | 'query'; + +export type Field = + | { + in: Exclude; + /** + * Field name. This is the name we want the user to see and use. + */ + key: string; + /** + * Field mapped name. This is the name we want to use in the request. + * If omitted, we use the same value as `key`. + */ + map?: string; + } + | { + in: Extract; + /** + * Key isn't required for bodies. + */ + key?: string; + map?: string; + } + | { + /** + * Field name. This is the name we want the user to see and use. + */ + key: string; + /** + * Field mapped name. This is the name we want to use in the request. + * If `in` is omitted, `map` aliases `key` to the transport layer. + */ + map: Slot; + }; + +export interface Fields { + allowExtra?: Partial>; + args?: ReadonlyArray; +} + +export type FieldsConfig = ReadonlyArray; + +const extraPrefixesMap: Record = { + $body_: 'body', + $headers_: 'headers', + $path_: 'path', + $query_: 'query', +}; +const extraPrefixes = Object.entries(extraPrefixesMap); + +type KeyMap = Map< + string, + | { + in: Slot; + map?: string; + } + | { + in?: never; + map: Slot; + } +>; + +const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { + if (!map) { + map = new Map(); + } + + for (const config of fields) { + if ('in' in config) { + if (config.key) { + map.set(config.key, { + in: config.in, + map: config.map, + }); + } + } else if ('key' in config) { + map.set(config.key, { + map: config.map, + }); + } else if (config.args) { + buildKeyMap(config.args, map); + } + } + + return map; +}; + +interface Params { + body: unknown; + headers: Record; + path: Record; + query: Record; +} + +const stripEmptySlots = (params: Params) => { + for (const [slot, value] of Object.entries(params)) { + if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { + delete params[slot as Slot]; + } + } +}; + +export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { + const params: Params = { + body: {}, + headers: {}, + path: {}, + query: {}, + }; + + const map = buildKeyMap(fields); + + let config: FieldsConfig[number] | undefined; + + for (const [index, arg] of args.entries()) { + if (fields[index]) { + config = fields[index]; + } + + if (!config) { + continue; + } + + if ('in' in config) { + if (config.key) { + const field = map.get(config.key)!; + const name = field.map || config.key; + if (field.in) { + (params[field.in] as Record)[name] = arg; + } + } else { + params.body = arg; + } + } else { + for (const [key, value] of Object.entries(arg ?? {})) { + const field = map.get(key); + + if (field) { + if (field.in) { + const name = field.map || key; + (params[field.in] as Record)[name] = value; + } else { + params[field.map] = value; + } + } else { + const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); + + if (extra) { + const [prefix, slot] = extra; + (params[slot] as Record)[key.slice(prefix.length)] = value; + } else if ('allowExtra' in config && config.allowExtra) { + for (const [slot, allowed] of Object.entries(config.allowExtra)) { + if (allowed) { + (params[slot as Slot] as Record)[key] = value; + break; + } + } + } + } + } + } + } + + stripEmptySlots(params); + + return params; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/pathSerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/pathSerializer.gen.ts new file mode 100644 index 0000000000..994b2848c6 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/pathSerializer.gen.ts @@ -0,0 +1,171 @@ +// This file is auto-generated by @hey-api/openapi-ts + +interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} + +interface SerializePrimitiveOptions { + allowReserved?: boolean; + name: string; +} + +export interface SerializerOptions { + /** + * @default true + */ + explode: boolean; + style: T; +} + +export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; +export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; +type MatrixStyle = 'label' | 'matrix' | 'simple'; +export type ObjectStyle = 'form' | 'deepObject'; +type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; + +interface SerializePrimitiveParam extends SerializePrimitiveOptions { + value: string; +} + +export const separatorArrayExplode = (style: ArraySeparatorStyle) => { + switch (style) { + case 'label': + return '.'; + case 'matrix': + return ';'; + case 'simple': + return ','; + default: + return '&'; + } +}; + +export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { + switch (style) { + case 'form': + return ','; + case 'pipeDelimited': + return '|'; + case 'spaceDelimited': + return '%20'; + default: + return ','; + } +}; + +export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { + switch (style) { + case 'label': + return '.'; + case 'matrix': + return ';'; + case 'simple': + return ','; + default: + return '&'; + } +}; + +export const serializeArrayParam = ({ + allowReserved, + explode, + name, + style, + value, +}: SerializeOptions & { + value: unknown[]; +}) => { + if (!explode) { + const joinedValues = ( + allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) + ).join(separatorArrayNoExplode(style)); + switch (style) { + case 'label': + return `.${joinedValues}`; + case 'matrix': + return `;${name}=${joinedValues}`; + case 'simple': + return joinedValues; + default: + return `${name}=${joinedValues}`; + } + } + + const separator = separatorArrayExplode(style); + const joinedValues = value + .map((v) => { + if (style === 'label' || style === 'simple') { + return allowReserved ? v : encodeURIComponent(v as string); + } + + return serializePrimitiveParam({ + allowReserved, + name, + value: v as string, + }); + }) + .join(separator); + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; +}; + +export const serializePrimitiveParam = ({ + allowReserved, + name, + value, +}: SerializePrimitiveParam) => { + if (value === undefined || value === null) { + return ''; + } + + if (typeof value === 'object') { + throw new Error( + 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', + ); + } + + return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; +}; + +export const serializeObjectParam = ({ + allowReserved, + explode, + name, + style, + value, + valueOnly, +}: SerializeOptions & { + value: Record | Date; + valueOnly?: boolean; +}) => { + if (value instanceof Date) { + return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; + } + + if (style !== 'deepObject' && !explode) { + let values: string[] = []; + Object.entries(value).forEach(([key, v]) => { + values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; + }); + const joinedValues = values.join(','); + switch (style) { + case 'form': + return `${name}=${joinedValues}`; + case 'label': + return `.${joinedValues}`; + case 'matrix': + return `;${name}=${joinedValues}`; + default: + return joinedValues; + } + } + + const separator = separatorObjectExplode(style); + const joinedValues = Object.entries(value) + .map(([key, v]) => + serializePrimitiveParam({ + allowReserved, + name: style === 'deepObject' ? `${name}[${key}]` : key, + value: v as string, + }), + ) + .join(separator); + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/queryKeySerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/queryKeySerializer.gen.ts new file mode 100644 index 0000000000..5000df606f --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/queryKeySerializer.gen.ts @@ -0,0 +1,117 @@ +// This file is auto-generated by @hey-api/openapi-ts + +/** + * JSON-friendly union that mirrors what Pinia Colada can hash. + */ +export type JsonValue = + | null + | string + | number + | boolean + | JsonValue[] + | { [key: string]: JsonValue }; + +/** + * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. + */ +export const queryKeyJsonReplacer = (_key: string, value: unknown) => { + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { + return undefined; + } + if (typeof value === 'bigint') { + return value.toString(); + } + if (value instanceof Date) { + return value.toISOString(); + } + return value; +}; + +/** + * Safely stringifies a value and parses it back into a JsonValue. + */ +export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { + try { + const json = JSON.stringify(input, queryKeyJsonReplacer); + if (json === undefined) { + return undefined; + } + return JSON.parse(json) as JsonValue; + } catch { + return undefined; + } +}; + +/** + * Detects plain objects (including objects with a null prototype). + */ +const isPlainObject = (value: unknown): value is Record => { + if (value === null || typeof value !== 'object') { + return false; + } + const prototype = Object.getPrototypeOf(value as object); + return prototype === Object.prototype || prototype === null; +}; + +/** + * Turns URLSearchParams into a sorted JSON object for deterministic keys. + */ +const serializeSearchParams = (params: URLSearchParams): JsonValue => { + const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); + const result: Record = {}; + + for (const [key, value] of entries) { + const existing = result[key]; + if (existing === undefined) { + result[key] = value; + continue; + } + + if (Array.isArray(existing)) { + (existing as string[]).push(value); + } else { + result[key] = [existing, value]; + } + } + + return result; +}; + +/** + * Normalizes any accepted value into a JSON-friendly shape for query keys. + */ +export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { + if (value === null) { + return null; + } + + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return value; + } + + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { + return undefined; + } + + if (typeof value === 'bigint') { + return value.toString(); + } + + if (value instanceof Date) { + return value.toISOString(); + } + + if (Array.isArray(value)) { + return stringifyToJsonValue(value); + } + + if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { + return serializeSearchParams(value); + } + + if (isPlainObject(value)) { + return stringifyToJsonValue(value); + } + + return undefined; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/serverSentEvents.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/serverSentEvents.gen.ts new file mode 100644 index 0000000000..6aa6cf02a4 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/serverSentEvents.gen.ts @@ -0,0 +1,243 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Config } from './types.gen'; + +export type ServerSentEventsOptions = Omit & + Pick & { + /** + * Fetch API implementation. You can use this option to provide a custom + * fetch instance. + * + * @default globalThis.fetch + */ + fetch?: typeof fetch; + /** + * Implementing clients can call request interceptors inside this hook. + */ + onRequest?: (url: string, init: RequestInit) => Promise; + /** + * Callback invoked when a network or parsing error occurs during streaming. + * + * This option applies only if the endpoint returns a stream of events. + * + * @param error The error that occurred. + */ + onSseError?: (error: unknown) => void; + /** + * Callback invoked when an event is streamed from the server. + * + * This option applies only if the endpoint returns a stream of events. + * + * @param event Event streamed from the server. + * @returns Nothing (void). + */ + onSseEvent?: (event: StreamEvent) => void; + serializedBody?: RequestInit['body']; + /** + * Default retry delay in milliseconds. + * + * This option applies only if the endpoint returns a stream of events. + * + * @default 3000 + */ + sseDefaultRetryDelay?: number; + /** + * Maximum number of retry attempts before giving up. + */ + sseMaxRetryAttempts?: number; + /** + * Maximum retry delay in milliseconds. + * + * Applies only when exponential backoff is used. + * + * This option applies only if the endpoint returns a stream of events. + * + * @default 30000 + */ + sseMaxRetryDelay?: number; + /** + * Optional sleep function for retry backoff. + * + * Defaults to using `setTimeout`. + */ + sseSleepFn?: (ms: number) => Promise; + url: string; + }; + +export interface StreamEvent { + data: TData; + event?: string; + id?: string; + retry?: number; +} + +export type ServerSentEventsResult = { + stream: AsyncGenerator< + TData extends Record ? TData[keyof TData] : TData, + TReturn, + TNext + >; +}; + +export const createSseClient = ({ + onRequest, + onSseError, + onSseEvent, + responseTransformer, + responseValidator, + sseDefaultRetryDelay, + sseMaxRetryAttempts, + sseMaxRetryDelay, + sseSleepFn, + url, + ...options +}: ServerSentEventsOptions): ServerSentEventsResult => { + let lastEventId: string | undefined; + + const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + + const createStream = async function* () { + let retryDelay: number = sseDefaultRetryDelay ?? 3000; + let attempt = 0; + const signal = options.signal ?? new AbortController().signal; + + while (true) { + if (signal.aborted) break; + + attempt++; + + const headers = + options.headers instanceof Headers + ? options.headers + : new Headers(options.headers as Record | undefined); + + if (lastEventId !== undefined) { + headers.set('Last-Event-ID', lastEventId); + } + + try { + const requestInit: RequestInit = { + redirect: 'follow', + ...options, + body: options.serializedBody, + headers, + signal, + }; + let request = new Request(url, requestInit); + if (onRequest) { + request = await onRequest(url, requestInit); + } + // fetch must be assigned here, otherwise it would throw the error: + // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation + const _fetch = options.fetch ?? globalThis.fetch; + const response = await _fetch(request); + + if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); + + if (!response.body) throw new Error('No body in SSE response'); + + const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); + + let buffer = ''; + + const abortHandler = () => { + try { + reader.cancel(); + } catch { + // noop + } + }; + + signal.addEventListener('abort', abortHandler); + + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + buffer += value; + // Normalize line endings: CRLF -> LF, then CR -> LF + buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); + + const chunks = buffer.split('\n\n'); + buffer = chunks.pop() ?? ''; + + for (const chunk of chunks) { + const lines = chunk.split('\n'); + const dataLines: Array = []; + let eventName: string | undefined; + + for (const line of lines) { + if (line.startsWith('data:')) { + dataLines.push(line.replace(/^data:\s*/, '')); + } else if (line.startsWith('event:')) { + eventName = line.replace(/^event:\s*/, ''); + } else if (line.startsWith('id:')) { + lastEventId = line.replace(/^id:\s*/, ''); + } else if (line.startsWith('retry:')) { + const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); + if (!Number.isNaN(parsed)) { + retryDelay = parsed; + } + } + } + + let data: unknown; + let parsedJson = false; + + if (dataLines.length) { + const rawData = dataLines.join('\n'); + try { + data = JSON.parse(rawData); + parsedJson = true; + } catch { + data = rawData; + } + } + + if (parsedJson) { + if (responseValidator) { + await responseValidator(data); + } + + if (responseTransformer) { + data = await responseTransformer(data); + } + } + + onSseEvent?.({ + data, + event: eventName, + id: lastEventId, + retry: retryDelay, + }); + + if (dataLines.length) { + yield data as any; + } + } + } + } finally { + signal.removeEventListener('abort', abortHandler); + reader.releaseLock(); + } + + break; // exit loop on normal completion + } catch (error) { + // connection failed or aborted; retry after delay + onSseError?.(error); + + if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { + break; // stop after firing error + } + + // exponential backoff: double retry each attempt, cap at 30s + const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); + await sleep(backoff); + } + } + }; + + const stream = createStream(); + + return { stream }; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/types.gen.ts new file mode 100644 index 0000000000..97463257e4 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/types.gen.ts @@ -0,0 +1,104 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Auth, AuthToken } from './auth.gen'; +import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; + +export type HttpMethod = + | 'connect' + | 'delete' + | 'get' + | 'head' + | 'options' + | 'patch' + | 'post' + | 'put' + | 'trace'; + +export type Client< + RequestFn = never, + Config = unknown, + MethodFn = never, + BuildUrlFn = never, + SseFn = never, +> = { + /** + * Returns the final request URL. + */ + buildUrl: BuildUrlFn; + getConfig: () => Config; + request: RequestFn; + setConfig: (config: Config) => Config; +} & { + [K in HttpMethod]: MethodFn; +} & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); + +export interface Config { + /** + * Auth token or a function returning auth token. The resolved value will be + * added to the request payload as defined by its `security` array. + */ + auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; + /** + * A function for serializing request body parameter. By default, + * {@link JSON.stringify()} will be used. + */ + bodySerializer?: BodySerializer | null; + /** + * An object containing any HTTP headers that you want to pre-populate your + * `Headers` object with. + * + * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} + */ + headers?: + | RequestInit['headers'] + | Record< + string, + string | number | boolean | (string | number | boolean)[] | null | undefined | unknown + >; + /** + * The request method. + * + * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} + */ + method?: Uppercase; + /** + * A function for serializing request query parameters. By default, arrays + * will be exploded in form style, objects will be exploded in deepObject + * style, and reserved characters are percent-encoded. + * + * This method will have no effect if the native `paramsSerializer()` Axios + * API function is used. + * + * {@link https://swagger.io/docs/specification/serialization/#query View examples} + */ + querySerializer?: QuerySerializer | QuerySerializerOptions; + /** + * A function validating request data. This is useful if you want to ensure + * the request conforms to the desired shape, so it can be safely sent to + * the server. + */ + requestValidator?: (data: unknown) => Promise; + /** + * A function transforming response data before it's returned. This is useful + * for post-processing data, e.g. converting ISO strings into Date objects. + */ + responseTransformer?: (data: unknown) => Promise; + /** + * A function validating response data. This is useful if you want to ensure + * the response conforms to the desired shape, so it can be safely passed to + * the transformers and returned to the user. + */ + responseValidator?: (data: unknown) => Promise; +} + +type IsExactlyNeverOrNeverUndefined = [T] extends [never] + ? true + : [T] extends [never | undefined] + ? [undefined] extends [T] + ? false + : true + : false; + +export type OmitNever> = { + [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/utils.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/utils.gen.ts new file mode 100644 index 0000000000..e7ddbe3541 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/core/utils.gen.ts @@ -0,0 +1,140 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; +import { + type ArraySeparatorStyle, + serializeArrayParam, + serializeObjectParam, + serializePrimitiveParam, +} from './pathSerializer.gen'; + +export interface PathSerializer { + path: Record; + url: string; +} + +export const PATH_PARAM_RE = /\{[^{}]+\}/g; + +export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { + let url = _url; + const matches = _url.match(PATH_PARAM_RE); + if (matches) { + for (const match of matches) { + let explode = false; + let name = match.substring(1, match.length - 1); + let style: ArraySeparatorStyle = 'simple'; + + if (name.endsWith('*')) { + explode = true; + name = name.substring(0, name.length - 1); + } + + if (name.startsWith('.')) { + name = name.substring(1); + style = 'label'; + } else if (name.startsWith(';')) { + name = name.substring(1); + style = 'matrix'; + } + + const value = path[name]; + + if (value === undefined || value === null) { + continue; + } + + if (Array.isArray(value)) { + url = url.replace(match, serializeArrayParam({ explode, name, style, value })); + continue; + } + + if (typeof value === 'object') { + url = url.replace( + match, + serializeObjectParam({ + explode, + name, + style, + value: value as Record, + valueOnly: true, + }), + ); + continue; + } + + if (style === 'matrix') { + url = url.replace( + match, + `;${serializePrimitiveParam({ + name, + value: value as string, + })}`, + ); + continue; + } + + const replaceValue = encodeURIComponent( + style === 'label' ? `.${value as string}` : (value as string), + ); + url = url.replace(match, replaceValue); + } + } + return url; +}; + +export const getUrl = ({ + baseUrl, + path, + query, + querySerializer, + url: _url, +}: { + baseUrl?: string; + path?: Record; + query?: Record; + querySerializer: QuerySerializer; + url: string; +}) => { + const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; + let url = (baseUrl ?? '') + pathUrl; + if (path) { + url = defaultPathSerializer({ path, url }); + } + let search = query ? querySerializer(query) : ''; + if (search.startsWith('?')) { + search = search.substring(1); + } + if (search) { + url += `?${search}`; + } + return url; +}; + +export function getValidRequestBody(options: { + body?: unknown; + bodySerializer?: BodySerializer | null; + serializedBody?: unknown; +}) { + const hasBody = options.body !== undefined; + const isSerializedBody = hasBody && options.bodySerializer; + + if (isSerializedBody) { + if ('serializedBody' in options) { + const hasSerializedBody = + options.serializedBody !== undefined && options.serializedBody !== ''; + + return hasSerializedBody ? options.serializedBody : null; + } + + // not all clients implement a serializedBody property (i.e. client-axios) + return options.body !== '' ? options.body : null; + } + + // plain/text body + if (hasBody) { + return options.body; + } + + // no body was provided + return undefined; +} diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/index.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/index.ts new file mode 100644 index 0000000000..6e132194fd --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/index.ts @@ -0,0 +1,4 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; +export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/sdk.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/sdk.gen.ts new file mode 100644 index 0000000000..e48dcff8cf --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/sdk.gen.ts @@ -0,0 +1,206 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; +import { client } from './client.gen'; +import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; + +export type Options = Options2 & { + /** + * You can provide a client instance returned by `createClient()` instead of + * individual options. This might be also useful if you want to implement a + * custom client. + */ + client?: Client; + /** + * You can pass arbitrary values through the `meta` object. This can be + * used to access values that aren't defined as part of the SDK function. + */ + meta?: Record; +}; + +export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); + +export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); + +export const import_ = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/no+tag', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); + +export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); + +export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); + +export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); + +export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); + +export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); + +export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); + +export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); + +export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); + +export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); + +export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); + +export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); + +/** + * @deprecated + */ +export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); + +export const callWithParameters = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/parameters/{parameterPath}', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ + url: '/api/v{api-version}/parameters', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/parameters', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ + url: '/api/v{api-version}/requestBody', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options?.headers + } +}); + +export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ + ...formDataBodySerializer, + url: '/api/v{api-version}/formData', + ...options, + headers: { + 'Content-Type': null, + ...options?.headers + } +}); + +export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); + +export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); + +export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); + +export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); + +export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); + +export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); + +export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); + +export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); + +export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); + +export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); + +export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); + +export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); + +export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); + +export const uploadFile = (options: Options) => (options.client ?? client).post({ + ...urlSearchParamsBodySerializer, + url: '/api/v{api-version}/upload', + ...options, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + ...options.headers + } +}); + +export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); + +export const complexTypes = (options: Options) => (options.client ?? client).get({ + querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, + url: '/api/v{api-version}/complex', + ...options +}); + +export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); + +export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ + ...formDataBodySerializer, + url: '/api/v{api-version}/multipart', + ...options, + headers: { + 'Content-Type': null, + ...options?.headers + } +}); + +export const complexParams = (options: Options) => (options.client ?? client).put({ + url: '/api/v{api-version}/complex/{id}', + ...options, + headers: { + 'Content-Type': 'application/json-patch+json', + ...options.headers + } +}); + +export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); + +export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); + +export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); + +/** + * Login User + */ +export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ + ...urlSearchParamsBodySerializer, + url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', + ...options, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + ...options.headers + } +}); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/types.gen.ts new file mode 100644 index 0000000000..d819316644 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/skipToken/types.gen.ts @@ -0,0 +1,2100 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type ClientOptions = { + baseUrl: 'http://localhost:3000/base' | (string & {}); +}; + +/** + * Model with number-only name + */ +export type _400 = string; + +/** + * External ref to shared model (A) + */ +export type ExternalRefA = ExternalSharedModel; + +/** + * External ref to shared model (B) + */ +export type ExternalRefB = ExternalSharedModel; + +/** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ +export type CamelCaseCommentWithBreaks = number; + +/** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ +export type CommentWithBreaks = number; + +/** + * Testing backticks in string: `backticks` and ```multiple backticks``` should work + */ +export type CommentWithBackticks = number; + +/** + * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work + */ +export type CommentWithBackticksAndQuotes = number; + +/** + * Testing slashes in string: \backwards\\\ and /forwards/// should work + */ +export type CommentWithSlashes = number; + +/** + * Testing expression placeholders in string: ${expression} should work + */ +export type CommentWithExpressionPlaceholders = number; + +/** + * Testing quotes in string: 'single quote''' and "double quotes""" should work + */ +export type CommentWithQuotes = number; + +/** + * Testing reserved characters in string: * inline * and ** inline ** should work + */ +export type CommentWithReservedCharacters = number; + +/** + * This is a simple number + */ +export type SimpleInteger = number; + +/** + * This is a simple boolean + */ +export type SimpleBoolean = boolean; + +/** + * This is a simple string + */ +export type SimpleString = string; + +/** + * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) + */ +export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; + +/** + * This is a simple file + */ +export type SimpleFile = Blob | File; + +/** + * This is a simple reference + */ +export type SimpleReference = ModelWithString; + +/** + * This is a simple string + */ +export type SimpleStringWithPattern = string | null; + +/** + * This is a simple enum with strings + */ +export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; + +export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; + +/** + * This is a simple enum with numbers + */ +export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; + +/** + * Success=1,Warning=2,Error=3 + */ +export type EnumFromDescription = number; + +/** + * This is a simple enum with numbers + */ +export type EnumWithExtensions = 200 | 400 | 500; + +export type EnumWithXEnumNames = 0 | 1 | 2; + +/** + * This is a simple array with numbers + */ +export type ArrayWithNumbers = Array; + +/** + * This is a simple array with booleans + */ +export type ArrayWithBooleans = Array; + +/** + * This is a simple array with strings + */ +export type ArrayWithStrings = Array; + +/** + * This is a simple array with references + */ +export type ArrayWithReferences = Array; + +/** + * This is a simple array containing an array + */ +export type ArrayWithArray = Array>; + +/** + * This is a simple array with properties + */ +export type ArrayWithProperties = Array<{ + '16x16'?: CamelCaseCommentWithBreaks; + bar?: string; +}>; + +/** + * This is a simple array with any of properties + */ +export type ArrayWithAnyOfProperties = Array<{ + foo?: string; +} | { + bar?: string; +}>; + +export type AnyOfAnyAndNull = { + data?: unknown | null; +}; + +/** + * This is a simple array with any of properties + */ +export type AnyOfArrays = { + results?: Array<{ + foo?: string; + } | { + bar?: string; + }>; +}; + +/** + * This is a string dictionary + */ +export type DictionaryWithString = { + [key: string]: string; +}; + +export type DictionaryWithPropertiesAndAdditionalProperties = { + foo?: number; + bar?: boolean; + [key: string]: string | number | boolean | undefined; +}; + +/** + * This is a string reference + */ +export type DictionaryWithReference = { + [key: string]: ModelWithString; +}; + +/** + * This is a complex dictionary + */ +export type DictionaryWithArray = { + [key: string]: Array; +}; + +/** + * This is a string dictionary + */ +export type DictionaryWithDictionary = { + [key: string]: { + [key: string]: string; + }; +}; + +/** + * This is a complex dictionary + */ +export type DictionaryWithProperties = { + [key: string]: { + foo?: string; + bar?: string; + }; +}; + +/** + * This is a model with one number property + */ +export type ModelWithInteger = { + /** + * This is a simple number property + */ + prop?: number; +}; + +/** + * This is a model with one boolean property + */ +export type ModelWithBoolean = { + /** + * This is a simple boolean property + */ + prop?: boolean; +}; + +/** + * This is a model with one string property + */ +export type ModelWithString = { + /** + * This is a simple string property + */ + prop?: string; +}; + +/** + * This is a model with one string property + */ +export type ModelWithStringError = { + /** + * This is a simple string property + */ + prop?: string; +}; + +/** + * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) + */ +export type ModelFromZendesk = string; + +/** + * This is a model with one string property + */ +export type ModelWithNullableString = { + /** + * This is a simple string property + */ + nullableProp1?: string | null; + /** + * This is a simple string property + */ + nullableRequiredProp1: string | null; + /** + * This is a simple string property + */ + nullableProp2?: string | null; + /** + * This is a simple string property + */ + nullableRequiredProp2: string | null; + /** + * This is a simple enum with strings + */ + 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; +}; + +/** + * This is a model with one enum + */ +export type ModelWithEnum = { + /** + * This is a simple enum with strings + */ + 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; + /** + * These are the HTTP error code enums + */ + statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; + /** + * Simple boolean enum + */ + bool?: true; +}; + +/** + * This is a model with one enum with escaped name + */ +export type ModelWithEnumWithHyphen = { + /** + * Foo-Bar-Baz-Qux + */ + 'foo-bar-baz-qux'?: '3.0'; +}; + +/** + * This is a model with one enum + */ +export type ModelWithEnumFromDescription = { + /** + * Success=1,Warning=2,Error=3 + */ + test?: number; +}; + +/** + * This is a model with nested enums + */ +export type ModelWithNestedEnums = { + dictionaryWithEnum?: { + [key: string]: 'Success' | 'Warning' | 'Error'; + }; + dictionaryWithEnumFromDescription?: { + [key: string]: number; + }; + arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; + arrayWithDescription?: Array; + /** + * This is a simple enum with strings + */ + 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; +}; + +/** + * This is a model with one property containing a reference + */ +export type ModelWithReference = { + prop?: ModelWithProperties; +}; + +/** + * This is a model with one property containing an array + */ +export type ModelWithArrayReadOnlyAndWriteOnly = { + prop?: Array; + propWithFile?: Array; + propWithNumber?: Array; +}; + +/** + * This is a model with one property containing an array + */ +export type ModelWithArray = { + prop?: Array; + propWithFile?: Array; + propWithNumber?: Array; +}; + +/** + * This is a model with one property containing a dictionary + */ +export type ModelWithDictionary = { + prop?: { + [key: string]: string; + }; +}; + +/** + * This is a deprecated model with a deprecated property + * + * @deprecated + */ +export type DeprecatedModel = { + /** + * This is a deprecated property + * + * @deprecated + */ + prop?: string; +}; + +/** + * This is a model with one property containing a circular reference + */ +export type ModelWithCircularReference = { + prop?: ModelWithCircularReference; +}; + +/** + * This is a model with one property with a 'one of' relationship + */ +export type CompositionWithOneOf = { + propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; +}; + +/** + * This is a model with one property with a 'one of' relationship where the options are not $ref + */ +export type CompositionWithOneOfAnonymous = { + propA?: { + propA?: string; + } | string | number; +}; + +/** + * Circle + */ +export type ModelCircle = { + kind: string; + radius?: number; +}; + +/** + * Square + */ +export type ModelSquare = { + kind: string; + sideLength?: number; +}; + +/** + * This is a model with one property with a 'one of' relationship where the options are not $ref + */ +export type CompositionWithOneOfDiscriminator = ({ + kind: 'circle'; +} & ModelCircle) | ({ + kind: 'square'; +} & ModelSquare); + +/** + * This is a model with one property with a 'any of' relationship + */ +export type CompositionWithAnyOf = { + propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; +}; + +/** + * This is a model with one property with a 'any of' relationship where the options are not $ref + */ +export type CompositionWithAnyOfAnonymous = { + propA?: { + propA?: string; + } | string | number; +}; + +/** + * This is a model with nested 'any of' property with a type null + */ +export type CompositionWithNestedAnyAndTypeNull = { + propA?: Array | Array; +}; + +export type _3eNum1Период = 'Bird' | 'Dog'; + +export type ConstValue = 'ConstValue'; + +/** + * This is a model with one property with a 'any of' relationship where the options are not $ref + */ +export type CompositionWithNestedAnyOfAndNull = { + /** + * Scopes + */ + propA?: Array<_3eNum1Период | ConstValue> | null; +}; + +/** + * This is a model with one property with a 'one of' relationship + */ +export type CompositionWithOneOfAndNullable = { + propA?: { + boolean?: boolean; + } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; +}; + +/** + * This is a model that contains a simple dictionary within composition + */ +export type CompositionWithOneOfAndSimpleDictionary = { + propA?: boolean | { + [key: string]: number; + }; +}; + +/** + * This is a model that contains a dictionary of simple arrays within composition + */ +export type CompositionWithOneOfAndSimpleArrayDictionary = { + propA?: boolean | { + [key: string]: Array; + }; +}; + +/** + * This is a model that contains a dictionary of complex arrays (composited) within composition + */ +export type CompositionWithOneOfAndComplexArrayDictionary = { + propA?: boolean | { + [key: string]: Array; + }; +}; + +/** + * This is a model with one property with a 'all of' relationship + */ +export type CompositionWithAllOfAndNullable = { + propA?: ({ + boolean?: boolean; + } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; +}; + +/** + * This is a model with one property with a 'any of' relationship + */ +export type CompositionWithAnyOfAndNullable = { + propA?: { + boolean?: boolean; + } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; +}; + +/** + * This is a base model with two simple optional properties + */ +export type CompositionBaseModel = { + firstName?: string; + lastname?: string; +}; + +/** + * This is a model that extends the base model + */ +export type CompositionExtendedModel = CompositionBaseModel & { + age: number; + firstName: string; + lastname: string; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithProperties = { + required: string; + readonly requiredAndReadOnly: string; + requiredAndNullable: string | null; + string?: string; + number?: number; + boolean?: boolean; + reference?: ModelWithString; + 'property with space'?: string; + default?: string; + try?: string; + readonly '@namespace.string'?: string; + readonly '@namespace.integer'?: number; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithNestedProperties = { + readonly first: { + readonly second: { + readonly third: string | null; + } | null; + } | null; +}; + +/** + * This is a model with duplicated properties + */ +export type ModelWithDuplicateProperties = { + prop?: ModelWithString; +}; + +/** + * This is a model with ordered properties + */ +export type ModelWithOrderedProperties = { + zebra?: string; + apple?: string; + hawaii?: string; +}; + +/** + * This is a model with duplicated imports + */ +export type ModelWithDuplicateImports = { + propA?: ModelWithString; + propB?: ModelWithString; + propC?: ModelWithString; +}; + +/** + * This is a model that extends another model + */ +export type ModelThatExtends = ModelWithString & { + propExtendsA?: string; + propExtendsB?: ModelWithString; +}; + +/** + * This is a model that extends another model + */ +export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { + propExtendsC?: string; + propExtendsD?: ModelWithString; +}; + +/** + * This is a model that contains a some patterns + */ +export type ModelWithPattern = { + key: string; + name: string; + readonly enabled?: boolean; + readonly modified?: string; + id?: string; + text?: string; + patternWithSingleQuotes?: string; + patternWithNewline?: string; + patternWithBacktick?: string; + patternWithUnicode?: string; +}; + +export type File = { + /** + * Id + */ + readonly id?: string; + /** + * Updated at + */ + readonly updated_at?: string; + /** + * Created at + */ + readonly created_at?: string; + /** + * Mime + */ + mime: string; + /** + * File + */ + readonly file?: string; +}; + +export type Default = { + name?: string; +}; + +export type Pageable = { + page?: number; + size?: number; + sort?: Array; +}; + +/** + * This is a free-form object without additionalProperties. + */ +export type FreeFormObjectWithoutAdditionalProperties = { + [key: string]: unknown; +}; + +/** + * This is a free-form object with additionalProperties: true. + */ +export type FreeFormObjectWithAdditionalPropertiesEqTrue = { + [key: string]: unknown; +}; + +/** + * This is a free-form object with additionalProperties: {}. + */ +export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { + [key: string]: unknown; +}; + +export type ModelWithConst = { + String?: 'String'; + number?: 0; + null?: null; + withType?: 'Some string'; +}; + +/** + * This is a model with one property and additionalProperties: true + */ +export type ModelWithAdditionalPropertiesEqTrue = { + /** + * This is a simple string property + */ + prop?: string; + [key: string]: unknown; +}; + +export type NestedAnyOfArraysNullable = { + nullableArray?: Array | null; +}; + +export type CompositionWithOneOfAndProperties = ({ + foo: SimpleParameter; +} | { + bar: NonAsciiStringæøåÆøÅöôêÊ字符串; +}) & { + baz: number | null; + qux: number; +}; + +/** + * An object that can be null + */ +export type NullableObject = { + foo?: string; +} | null; + +/** + * Some % character + */ +export type CharactersInDescription = string; + +export type ModelWithNullableObject = { + data?: NullableObject; +}; + +/** + * An object with additional properties that can be null (anyOf ref + null) + */ +export type ModelWithAdditionalPropertiesRef = { + [key: string]: NullableObject | null; +}; + +export type ModelWithOneOfEnum = { + foo: 'Bar'; +} | { + foo: 'Baz'; +} | { + foo: 'Qux'; +} | { + content: string; + foo: 'Quux'; +} | { + content: [ + string, + string + ]; + foo: 'Corge'; +}; + +export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; + +export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; + +export type ModelWithNestedArrayEnumsData = { + foo?: Array; + bar?: Array; +}; + +export type ModelWithNestedArrayEnums = { + array_strings?: Array; + data?: ModelWithNestedArrayEnumsData; +}; + +export type ModelWithNestedCompositionEnums = { + foo?: ModelWithNestedArrayEnumsDataFoo; +}; + +export type ModelWithReadOnlyAndWriteOnly = { + foo: string; + readonly bar: string; +}; + +export type ModelWithConstantSizeArray = [ + number, + number +]; + +export type ModelWithAnyOfConstantSizeArray = [ + number | string, + number | string, + number | string +]; + +export type ModelWithPrefixItemsConstantSizeArray = [ + ModelWithInteger, + number | string, + string +]; + +export type ModelWithAnyOfConstantSizeArrayNullable = [ + number | null | string, + number | null | string, + number | null | string +]; + +export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ + number | Import, + number | Import +]; + +export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ + number & string, + number & string +]; + +export type ModelWithNumericEnumUnion = { + /** + * Период + */ + value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; +}; + +/** + * Some description with `back ticks` + */ +export type ModelWithBackticksInDescription = { + /** + * The template `that` should be used for parsing and importing the contents of the CSV file. + * + *

There is one placeholder currently supported:

  • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

Example of a correct JSON template:

+ *
+     * [
+     * {
+     * "resourceType": "Asset",
+     * "identifier": {
+     * "name": "${1}",
+     * "domain": {
+     * "name": "${2}",
+     * "community": {
+     * "name": "Some Community"
+     * }
+     * }
+     * },
+     * "attributes" : {
+     * "00000000-0000-0000-0000-000000003115" : [ {
+     * "value" : "${3}"
+     * } ],
+     * "00000000-0000-0000-0000-000000000222" : [ {
+     * "value" : "${4}"
+     * } ]
+     * }
+     * }
+     * ]
+     * 
+ */ + template?: string; +}; + +export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { + baz: number | null; + qux: number; +}; + +/** + * Model used to test deduplication strategy (unused) + */ +export type ParameterSimpleParameterUnused = string; + +/** + * Model used to test deduplication strategy + */ +export type PostServiceWithEmptyTagResponse = string; + +/** + * Model used to test deduplication strategy + */ +export type PostServiceWithEmptyTagResponse2 = string; + +/** + * Model used to test deduplication strategy + */ +export type DeleteFooData = string; + +/** + * Model used to test deduplication strategy + */ +export type DeleteFooData2 = string; + +/** + * Model with restricted keyword name + */ +export type Import = string; + +export type SchemaWithFormRestrictedKeys = { + description?: string; + 'x-enum-descriptions'?: string; + 'x-enum-varnames'?: string; + 'x-enumNames'?: string; + title?: string; + object?: { + description?: string; + 'x-enum-descriptions'?: string; + 'x-enum-varnames'?: string; + 'x-enumNames'?: string; + title?: string; + }; + array?: Array<{ + description?: string; + 'x-enum-descriptions'?: string; + 'x-enum-varnames'?: string; + 'x-enumNames'?: string; + title?: string; + }>; +}; + +/** + * This schema was giving PascalCase transformations a hard time + */ +export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { + /** + * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. + */ + preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; +}; + +/** + * This schema was giving PascalCase transformations a hard time + */ +export type IoK8sApimachineryPkgApisMetaV1Preconditions = { + /** + * Specifies the target ResourceVersion + */ + resourceVersion?: string; + /** + * Specifies the target UID. + */ + uid?: string; +}; + +export type AdditionalPropertiesUnknownIssue = { + [key: string]: string | number; +}; + +export type AdditionalPropertiesUnknownIssue2 = { + [key: string]: string | number; +}; + +export type AdditionalPropertiesUnknownIssue3 = string & { + entries: { + [key: string]: AdditionalPropertiesUnknownIssue; + }; +}; + +export type AdditionalPropertiesIntegerIssue = { + value: number; + [key: string]: number; +}; + +export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; + +export type GenericSchemaDuplicateIssue1SystemBoolean = { + item?: boolean; + error?: string | null; + readonly hasError?: boolean; + data?: { + [key: string]: never; + }; +}; + +export type GenericSchemaDuplicateIssue1SystemString = { + item?: string | null; + error?: string | null; + readonly hasError?: boolean; +}; + +export type ExternalSharedModel = { + id: string; + name?: string; +}; + +/** + * This is a model with one property containing a reference + */ +export type ModelWithReferenceWritable = { + prop?: ModelWithPropertiesWritable; +}; + +/** + * This is a model with one property containing an array + */ +export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { + prop?: Array; + propWithFile?: Array; + propWithNumber?: Array; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithPropertiesWritable = { + required: string; + requiredAndNullable: string | null; + string?: string; + number?: number; + boolean?: boolean; + reference?: ModelWithString; + 'property with space'?: string; + default?: string; + try?: string; +}; + +/** + * This is a model that contains a some patterns + */ +export type ModelWithPatternWritable = { + key: string; + name: string; + id?: string; + text?: string; + patternWithSingleQuotes?: string; + patternWithNewline?: string; + patternWithBacktick?: string; + patternWithUnicode?: string; +}; + +export type FileWritable = { + /** + * Mime + */ + mime: string; +}; + +export type ModelWithReadOnlyAndWriteOnlyWritable = { + foo: string; + baz: string; +}; + +export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ + number | Import, + number | Import +]; + +export type AdditionalPropertiesUnknownIssueWritable = { + [key: string]: string | number; +}; + +export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; + +export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { + item?: boolean; + error?: string | null; + data?: { + [key: string]: never; + }; +}; + +export type GenericSchemaDuplicateIssue1SystemStringWritable = { + item?: string | null; + error?: string | null; +}; + +/** + * This is a reusable parameter + */ +export type SimpleParameter = string; + +/** + * Parameter with illegal characters + */ +export type XFooBar = ModelWithString; + +/** + * A reusable request body + */ +export type SimpleRequestBody = ModelWithString; + +/** + * A reusable request body + */ +export type SimpleFormData = ModelWithString; + +export type ExportData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type PatchApiVbyApiVersionNoTagData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type PatchApiVbyApiVersionNoTagResponses = { + /** + * OK + */ + default: unknown; +}; + +export type ImportData = { + body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type ImportResponses = { + /** + * Success + */ + 200: ModelFromZendesk; + /** + * Default success response + */ + default: ModelWithReadOnlyAndWriteOnly; +}; + +export type ImportResponse = ImportResponses[keyof ImportResponses]; + +export type FooWowData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type FooWowResponses = { + /** + * OK + */ + default: unknown; +}; + +export type ApiVVersionODataControllerCountData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple/$count'; +}; + +export type ApiVVersionODataControllerCountResponses = { + /** + * Success + */ + 200: ModelFromZendesk; +}; + +export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; + +export type GetApiVbyApiVersionSimpleOperationData = { + body?: never; + path: { + /** + * foo in method + */ + foo_param: string; + }; + query?: never; + url: '/api/v{api-version}/simple:operation'; +}; + +export type GetApiVbyApiVersionSimpleOperationErrors = { + /** + * Default error response + */ + default: ModelWithBoolean; +}; + +export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; + +export type GetApiVbyApiVersionSimpleOperationResponses = { + /** + * Response is a simple number + */ + 200: number; +}; + +export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; + +export type DeleteCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type GetCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type HeadCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type OptionsCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PatchCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PostCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PutCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type DeleteFooData3 = { + body?: never; + headers: { + /** + * Parameter with illegal characters + */ + 'x-Foo-Bar': ModelWithString; + }; + path: { + /** + * foo in method + */ + foo_param: string; + /** + * bar in method + */ + BarParam: string; + }; + query?: never; + url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; +}; + +export type CallWithDescriptionsData = { + body?: never; + path?: never; + query?: { + /** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ + parameterWithBreaks?: string; + /** + * Testing backticks in string: `backticks` and ```multiple backticks``` should work + */ + parameterWithBackticks?: string; + /** + * Testing slashes in string: \backwards\\\ and /forwards/// should work + */ + parameterWithSlashes?: string; + /** + * Testing expression placeholders in string: ${expression} should work + */ + parameterWithExpressionPlaceholders?: string; + /** + * Testing quotes in string: 'single quote''' and "double quotes""" should work + */ + parameterWithQuotes?: string; + /** + * Testing reserved characters in string: * inline * and ** inline ** should work + */ + parameterWithReservedCharacters?: string; + }; + url: '/api/v{api-version}/descriptions'; +}; + +export type DeprecatedCallData = { + body?: never; + headers: { + /** + * This parameter is deprecated + * + * @deprecated + */ + parameter: DeprecatedModel | null; + }; + path?: never; + query?: never; + url: '/api/v{api-version}/parameters/deprecated'; +}; + +export type CallWithParametersData = { + /** + * This is the parameter that goes into the body + */ + body: { + [key: string]: unknown; + } | null; + headers: { + /** + * This is the parameter that goes into the header + */ + parameterHeader: string | null; + }; + path: { + /** + * This is the parameter that goes into the path + */ + parameterPath: string | null; + /** + * api-version should be required in standalone clients + */ + 'api-version': string | null; + }; + query: { + foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; + foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; + /** + * This is the parameter that goes into the query params + */ + cursor: string | null; + }; + url: '/api/v{api-version}/parameters/{parameterPath}'; +}; + +export type CallWithWeirdParameterNamesData = { + /** + * This is the parameter that goes into the body + */ + body: ModelWithString | null; + headers: { + /** + * This is the parameter that goes into the request header + */ + 'parameter.header': string | null; + }; + path: { + /** + * This is the parameter that goes into the path + */ + 'parameter.path.1'?: string; + /** + * This is the parameter that goes into the path + */ + 'parameter-path-2'?: string; + /** + * This is the parameter that goes into the path + */ + 'PARAMETER-PATH-3'?: string; + /** + * api-version should be required in standalone clients + */ + 'api-version': string | null; + }; + query: { + /** + * This is the parameter with a reserved keyword + */ + default?: string; + /** + * This is the parameter that goes into the request query params + */ + 'parameter-query': string | null; + }; + url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; +}; + +export type GetCallWithOptionalParamData = { + /** + * This is a required parameter + */ + body: ModelWithOneOfEnum; + path?: never; + query?: { + /** + * This is an optional parameter + */ + page?: number; + }; + url: '/api/v{api-version}/parameters'; +}; + +export type PostCallWithOptionalParamData = { + /** + * This is an optional parameter + */ + body?: { + offset?: number | null; + }; + path?: never; + query: { + /** + * This is a required parameter + */ + parameter: Pageable; + }; + url: '/api/v{api-version}/parameters'; +}; + +export type PostCallWithOptionalParamResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Success + */ + 204: void; +}; + +export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; + +export type PostApiVbyApiVersionRequestBodyData = { + /** + * A reusable request body + */ + body?: SimpleRequestBody; + path?: never; + query?: { + /** + * This is a reusable parameter + */ + parameter?: string; + }; + url: '/api/v{api-version}/requestBody'; +}; + +export type PostApiVbyApiVersionFormDataData = { + /** + * A reusable request body + */ + body?: SimpleFormData; + path?: never; + query?: { + /** + * This is a reusable parameter + */ + parameter?: string; + }; + url: '/api/v{api-version}/formData'; +}; + +export type CallWithDefaultParametersData = { + body?: never; + path?: never; + query?: { + /** + * This is a simple string with default value + */ + parameterString?: string | null; + /** + * This is a simple number with default value + */ + parameterNumber?: number | null; + /** + * This is a simple boolean with default value + */ + parameterBoolean?: boolean | null; + /** + * This is a simple enum with default value + */ + parameterEnum?: 'Success' | 'Warning' | 'Error'; + /** + * This is a simple model with default value + */ + parameterModel?: ModelWithString | null; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type CallWithDefaultOptionalParametersData = { + body?: never; + path?: never; + query?: { + /** + * This is a simple string that is optional with default value + */ + parameterString?: string; + /** + * This is a simple number that is optional with default value + */ + parameterNumber?: number; + /** + * This is a simple boolean that is optional with default value + */ + parameterBoolean?: boolean; + /** + * This is a simple enum that is optional with default value + */ + parameterEnum?: 'Success' | 'Warning' | 'Error'; + /** + * This is a simple model that is optional with default value + */ + parameterModel?: ModelWithString; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type CallToTestOrderOfParamsData = { + body?: never; + path?: never; + query: { + /** + * This is a optional string with default + */ + parameterOptionalStringWithDefault?: string; + /** + * This is a optional string with empty default + */ + parameterOptionalStringWithEmptyDefault?: string; + /** + * This is a optional string with no default + */ + parameterOptionalStringWithNoDefault?: string; + /** + * This is a string with default + */ + parameterStringWithDefault: string; + /** + * This is a string with empty default + */ + parameterStringWithEmptyDefault: string; + /** + * This is a string with no default + */ + parameterStringWithNoDefault: string; + /** + * This is a string that can be null with no default + */ + parameterStringNullableWithNoDefault?: string | null; + /** + * This is a string that can be null with default + */ + parameterStringNullableWithDefault?: string | null; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type DuplicateNameData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName2Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName3Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName4Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type CallWithNoContentResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no-content'; +}; + +export type CallWithNoContentResponseResponses = { + /** + * Success + */ + 204: void; +}; + +export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; + +export type CallWithResponseAndNoContentResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/response-and-no-content'; +}; + +export type CallWithResponseAndNoContentResponseResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Success + */ + 204: void; +}; + +export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; + +export type DummyAData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/a'; +}; + +export type DummyAResponses = { + 200: _400; +}; + +export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; + +export type DummyBData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/b'; +}; + +export type DummyBResponses = { + /** + * Success + */ + 204: void; +}; + +export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; + +export type CallWithResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithResponseResponses = { + default: Import; +}; + +export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; + +export type CallWithDuplicateResponsesData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithDuplicateResponsesErrors = { + /** + * Message for 500 error + */ + 500: ModelWithStringError; + /** + * Message for 501 error + */ + 501: ModelWithStringError; + /** + * Message for 502 error + */ + 502: ModelWithStringError; + /** + * Message for 4XX errors + */ + '4XX': DictionaryWithArray; + /** + * Default error response + */ + default: ModelWithBoolean; +}; + +export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; + +export type CallWithDuplicateResponsesResponses = { + /** + * Message for 200 response + */ + 200: ModelWithBoolean & ModelWithInteger; + /** + * Message for 201 response + */ + 201: ModelWithString; + /** + * Message for 202 response + */ + 202: ModelWithString; +}; + +export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; + +export type CallWithResponsesData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithResponsesErrors = { + /** + * Message for 500 error + */ + 500: ModelWithStringError; + /** + * Message for 501 error + */ + 501: ModelWithStringError; + /** + * Message for 502 error + */ + 502: ModelWithStringError; + /** + * Message for default response + */ + default: ModelWithStringError; +}; + +export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; + +export type CallWithResponsesResponses = { + /** + * Message for 200 response + */ + 200: { + readonly '@namespace.string'?: string; + readonly '@namespace.integer'?: number; + readonly value?: Array; + }; + /** + * Message for 201 response + */ + 201: ModelThatExtends; + /** + * Message for 202 response + */ + 202: ModelThatExtendsExtends; +}; + +export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; + +export type CollectionFormatData = { + body?: never; + path?: never; + query: { + /** + * This is an array parameter that is sent as csv format (comma-separated values) + */ + parameterArrayCSV: Array | null; + /** + * This is an array parameter that is sent as ssv format (space-separated values) + */ + parameterArraySSV: Array | null; + /** + * This is an array parameter that is sent as tsv format (tab-separated values) + */ + parameterArrayTSV: Array | null; + /** + * This is an array parameter that is sent as pipes format (pipe-separated values) + */ + parameterArrayPipes: Array | null; + /** + * This is an array parameter that is sent as multi format (multiple parameter instances) + */ + parameterArrayMulti: Array | null; + }; + url: '/api/v{api-version}/collectionFormat'; +}; + +export type TypesData = { + body?: never; + path?: { + /** + * This is a number parameter + */ + id?: number; + }; + query: { + /** + * This is a number parameter + */ + parameterNumber: number; + /** + * This is a string parameter + */ + parameterString: string | null; + /** + * This is a boolean parameter + */ + parameterBoolean: boolean | null; + /** + * This is an object parameter + */ + parameterObject: { + [key: string]: unknown; + } | null; + /** + * This is an array parameter + */ + parameterArray: Array | null; + /** + * This is a dictionary parameter + */ + parameterDictionary: { + [key: string]: unknown; + } | null; + /** + * This is an enum parameter + */ + parameterEnum: 'Success' | 'Warning' | 'Error' | null; + }; + url: '/api/v{api-version}/types'; +}; + +export type TypesResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Response is a simple string + */ + 201: string; + /** + * Response is a simple boolean + */ + 202: boolean; + /** + * Response is a simple object + */ + 203: { + [key: string]: unknown; + }; +}; + +export type TypesResponse = TypesResponses[keyof TypesResponses]; + +export type UploadFileData = { + body: Blob | File; + path: { + /** + * api-version should be required in standalone clients + */ + 'api-version': string | null; + }; + query?: never; + url: '/api/v{api-version}/upload'; +}; + +export type UploadFileResponses = { + 200: boolean; +}; + +export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; + +export type FileResponseData = { + body?: never; + path: { + id: string; + /** + * api-version should be required in standalone clients + */ + 'api-version': string; + }; + query?: never; + url: '/api/v{api-version}/file/{id}'; +}; + +export type FileResponseResponses = { + /** + * Success + */ + 200: Blob | File; +}; + +export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; + +export type ComplexTypesData = { + body?: never; + path?: never; + query: { + /** + * Parameter containing object + */ + parameterObject: { + first?: { + second?: { + third?: string; + }; + }; + }; + /** + * Parameter containing reference + */ + parameterReference: ModelWithString; + }; + url: '/api/v{api-version}/complex'; +}; + +export type ComplexTypesErrors = { + /** + * 400 `server` error + */ + 400: unknown; + /** + * 500 server error + */ + 500: unknown; +}; + +export type ComplexTypesResponses = { + /** + * Successful response + */ + 200: Array; +}; + +export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; + +export type MultipartResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multipart'; +}; + +export type MultipartResponseResponses = { + /** + * OK + */ + 200: { + file?: Blob | File; + metadata?: { + foo?: string; + bar?: string; + }; + }; +}; + +export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; + +export type MultipartRequestData = { + body?: { + content?: Blob | File; + data?: ModelWithString | null; + }; + path?: never; + query?: never; + url: '/api/v{api-version}/multipart'; +}; + +export type ComplexParamsData = { + body?: { + readonly key: string | null; + name: string | null; + enabled?: boolean; + type: 'Monkey' | 'Horse' | 'Bird'; + listOfModels?: Array | null; + listOfStrings?: Array | null; + parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; + readonly user?: { + readonly id?: number; + readonly name?: string | null; + }; + }; + path: { + id: number; + /** + * api-version should be required in standalone clients + */ + 'api-version': string; + }; + query?: never; + url: '/api/v{api-version}/complex/{id}'; +}; + +export type ComplexParamsResponses = { + /** + * Success + */ + 200: ModelWithString; +}; + +export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; + +export type CallWithResultFromHeaderData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/header'; +}; + +export type CallWithResultFromHeaderErrors = { + /** + * 400 server error + */ + 400: unknown; + /** + * 500 server error + */ + 500: unknown; +}; + +export type CallWithResultFromHeaderResponses = { + /** + * Successful response + */ + 200: unknown; +}; + +export type TestErrorCodeData = { + body?: never; + path?: never; + query: { + /** + * Status code to return + */ + status: number; + }; + url: '/api/v{api-version}/error'; +}; + +export type TestErrorCodeErrors = { + /** + * Custom message: Internal Server Error + */ + 500: unknown; + /** + * Custom message: Not Implemented + */ + 501: unknown; + /** + * Custom message: Bad Gateway + */ + 502: unknown; + /** + * Custom message: Service Unavailable + */ + 503: unknown; +}; + +export type TestErrorCodeResponses = { + /** + * Custom message: Successful response + */ + 200: unknown; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Data = { + body?: never; + path?: never; + query: { + /** + * Dummy input param + */ + nonAsciiParamæøåÆØÅöôêÊ: number; + }; + url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { + /** + * Successful response + */ + 200: Array; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; + +export type PutWithFormUrlEncodedData = { + body: ArrayWithStrings; + path?: never; + query?: never; + url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useMutation/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useMutation/@tanstack/react-query.gen.ts index 3bb1f02eec..bbc1eeb48a 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useMutation/@tanstack/react-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useMutation/@tanstack/react-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, useMutation, type UseMutationOptions } from '@tanstack/react-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, skipToken, useMutation, type UseMutationOptions, useQuery } from '@tanstack/react-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -50,10 +54,22 @@ export const exportOptions = (options?: Options) => queryOptions) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useExportQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(exportOptions, options); + export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -104,8 +120,8 @@ export const useFooWowMutation = (mutationOptions?: Partial) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -113,14 +129,18 @@ export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(apiVVersionODataControllerCountOptions, options); + export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -128,10 +148,14 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getApiVbyApiVersionSimpleOperationOptions, options); + export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -150,8 +174,8 @@ export const useDeleteCallWithoutParametersAndResponseMutation = (mutationOption export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -159,10 +183,14 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithoutParametersAndResponseOptions, options); + export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -299,8 +327,8 @@ export const useCallWithWeirdParameterNamesMutation = (mutationOptions?: Partial export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -308,8 +336,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -343,10 +371,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -361,10 +389,14 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithOptionalParamOptions, options); + export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -415,8 +447,8 @@ export const usePostApiVbyApiVersionFormDataMutation = (mutationOptions?: Partia export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -424,10 +456,14 @@ export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithDefaultParametersOptions, options); + export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -478,8 +514,8 @@ export const useDuplicateNameMutation = (mutationOptions?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -487,10 +523,14 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); +export const useDuplicateName2Query = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(duplicateName2Options, options); + export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -525,8 +565,8 @@ export const useDuplicateName4Mutation = (mutationOptions?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -534,14 +574,18 @@ export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithNoContentResponseOptions, options); + export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -549,14 +593,18 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseAndNoContentResponseOptions, options); + export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -564,14 +612,18 @@ export const dummyAOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyAOptions, options); + export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -579,14 +631,18 @@ export const dummyBOptions = (options?: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyBOptions, options); + export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -594,10 +650,14 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); +export const useCallWithResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseOptions, options); + export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -632,8 +692,8 @@ export const useCallWithResponsesMutation = (mutationOptions?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -641,14 +701,18 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); +export const useCollectionFormatQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(collectionFormatOptions, options); + export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -656,10 +720,14 @@ export const typesOptions = (options: Options) => queryOptions | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(typesOptions, options); + export const uploadFileMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { @@ -678,8 +746,8 @@ export const useUploadFileMutation = (mutationOptions?: Partial) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -687,14 +755,18 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); +export const useFileResponseQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(fileResponseOptions, options); + export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -702,14 +774,18 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); +export const useComplexTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(complexTypesOptions, options); + export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -717,10 +793,14 @@ export const multipartResponseOptions = (options?: Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(multipartResponseOptions, options); + export const multipartRequestMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { mutationFn: async (fnOptions) => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/@tanstack/react-query.gen.ts new file mode 100644 index 0000000000..63173ae9d9 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/@tanstack/react-query.gen.ts @@ -0,0 +1,764 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, skipToken, type UseMutationOptions } from '@tanstack/react-query'; + +import { client } from '../client.gen'; +import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; +import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; + +export type QueryKey = [ + Pick & { + _id: string; + _infinite?: boolean; + tags?: ReadonlyArray; + } +]; + +const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ + QueryKey[0] +] => { + const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; + if (infinite) { + params._infinite = infinite; + } + if (tags) { + params.tags = tags; + } + if (options?.body) { + params.body = options.body; + } + if (options?.headers) { + params.headers = options.headers; + } + if (options?.path) { + params.path = options.path; + } + if (options?.query) { + params.query = options.query; + } + return [params]; +}; + +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + +export const exportQueryKey = (options?: Options) => createQueryKey('export', options); + +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await export_({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: exportQueryKey(resolveOptions(options)) +}); + +export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await patchApiVbyApiVersionNoTag({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const importMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await import_({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const fooWowMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await fooWow({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); + +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await apiVVersionODataControllerCount({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: apiVVersionODataControllerCountQueryKey(resolveOptions(options)) +}); + +export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); + +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await getApiVbyApiVersionSimpleOperation({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: getApiVbyApiVersionSimpleOperationQueryKey(resolveOptions(options)) +}); + +export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deleteCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); + +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await getCallWithoutParametersAndResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: getCallWithoutParametersAndResponseQueryKey(resolveOptions(options)) +}); + +export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await patchCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await putCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const deleteFooMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deleteFoo({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDescriptions({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * @deprecated + */ +export const deprecatedCallMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deprecatedCall({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithParametersMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithParameters({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithWeirdParameterNames({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); + +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await getCallWithOptionalParam({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: getCallWithOptionalParamQueryKey(resolveOptions(options)) +}); + +const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { + const params = { ...queryKey[0] }; + if (page.body) { + params.body = { + ...queryKey[0].body as any, + ...page.body as any + }; + } + if (page.headers) { + params.headers = { + ...queryKey[0].headers, + ...page.headers + }; + } + if (page.path) { + params.path = { + ...queryKey[0].path as any, + ...page.path as any + }; + } + if (page.query) { + params.query = { + ...queryKey[0].query as any, + ...page.query as any + }; + } + return params as unknown as typeof page; +}; + +export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); + +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +// @ts-ignore +{ + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { + // @ts-ignore + const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { + query: { + page: pageParam + } + }; + const params = createInfiniteParams(queryKey, page); + const { data } = await getCallWithOptionalParam({ + ...options, + ...params, + signal, + throwOnError: true + }); + return data; + }), + queryKey: getCallWithOptionalParamInfiniteQueryKey(resolveOptions(options)) +}); + +export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postCallWithOptionalParam({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postApiVbyApiVersionRequestBody({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postApiVbyApiVersionFormData({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); + +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithDefaultParameters({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithDefaultParametersQueryKey(resolveOptions(options)) +}); + +export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDefaultOptionalParameters({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callToTestOrderOfParams({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateNameMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); + +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await duplicateName2({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) +}); + +export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName3({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName4({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); + +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithNoContentResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithNoContentResponseQueryKey(resolveOptions(options)) +}); + +export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); + +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithResponseAndNoContentResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithResponseAndNoContentResponseQueryKey(resolveOptions(options)) +}); + +export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); + +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await dummyA({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: dummyAQueryKey(resolveOptions(options)) +}); + +export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); + +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await dummyB({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: dummyBQueryKey(resolveOptions(options)) +}); + +export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); + +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) +}); + +export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDuplicateResponses({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithResponses({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); + +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await collectionFormat({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) +}); + +export const typesQueryKey = (options: Options) => createQueryKey('types', options); + +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await types({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: typesQueryKey(resolveOptions(options)) +}); + +export const uploadFileMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await uploadFile({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); + +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await fileResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) +}); + +export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); + +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await complexTypes({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) +}); + +export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); + +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await multipartResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: multipartResponseQueryKey(resolveOptions(options)) +}); + +export const multipartRequestMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await multipartRequest({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const complexParamsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await complexParams({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithResultFromHeader({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await testErrorCode({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * Login User + */ +export const putWithFormUrlEncodedMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await putWithFormUrlEncoded({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/client.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/client.gen.ts new file mode 100644 index 0000000000..25cd14eafb --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/client.gen.ts @@ -0,0 +1,16 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type ClientOptions, type Config, createClient, createConfig } from './client'; +import type { ClientOptions as ClientOptions2 } from './types.gen'; + +/** + * The `createClientConfig()` function will be called on client initialization + * and the returned object will become the client's initial configuration. + * + * You may want to initialize your client this way instead of calling + * `setConfig()`. This is useful for example if you're using Next.js + * to ensure your client always has the correct values. + */ +export type CreateClientConfig = (override?: Config) => Config & T>; + +export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/client/client.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/client/client.gen.ts new file mode 100644 index 0000000000..14dc0a0ec5 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/client/client.gen.ts @@ -0,0 +1,290 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { createSseClient } from '../core/serverSentEvents.gen'; +import type { HttpMethod } from '../core/types.gen'; +import { getValidRequestBody } from '../core/utils.gen'; +import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; +import { + buildUrl, + createConfig, + createInterceptors, + getParseAs, + mergeConfigs, + mergeHeaders, + setAuthParams, +} from './utils.gen'; + +type ReqInit = Omit & { + body?: any; + headers: ReturnType; +}; + +export const createClient = (config: Config = {}): Client => { + let _config = mergeConfigs(createConfig(), config); + + const getConfig = (): Config => ({ ..._config }); + + const setConfig = (config: Config): Config => { + _config = mergeConfigs(_config, config); + return getConfig(); + }; + + const interceptors = createInterceptors(); + + const beforeRequest = async (options: RequestOptions) => { + const opts = { + ..._config, + ...options, + fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, + headers: mergeHeaders(_config.headers, options.headers), + serializedBody: undefined as string | undefined, + }; + + if (opts.security) { + await setAuthParams({ + ...opts, + security: opts.security, + }); + } + + if (opts.requestValidator) { + await opts.requestValidator(opts); + } + + if (opts.body !== undefined && opts.bodySerializer) { + opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; + } + + // remove Content-Type header if body is empty to avoid sending invalid requests + if (opts.body === undefined || opts.serializedBody === '') { + opts.headers.delete('Content-Type'); + } + + const url = buildUrl(opts); + + return { opts, url }; + }; + + const request: Client['request'] = async (options) => { + // @ts-expect-error + const { opts, url } = await beforeRequest(options); + const requestInit: ReqInit = { + redirect: 'follow', + ...opts, + body: getValidRequestBody(opts), + }; + + let request = new Request(url, requestInit); + + for (const fn of interceptors.request.fns) { + if (fn) { + request = await fn(request, opts); + } + } + + // fetch must be assigned here, otherwise it would throw the error: + // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation + const _fetch = opts.fetch!; + let response: Response; + + try { + response = await _fetch(request); + } catch (error) { + // Handle fetch exceptions (AbortError, network errors, etc.) + let finalError = error; + + for (const fn of interceptors.error.fns) { + if (fn) { + finalError = (await fn(error, undefined as any, request, opts)) as unknown; + } + } + + finalError = finalError || ({} as unknown); + + if (opts.throwOnError) { + throw finalError; + } + + // Return error response + return opts.responseStyle === 'data' + ? undefined + : { + error: finalError, + request, + response: undefined as any, + }; + } + + for (const fn of interceptors.response.fns) { + if (fn) { + response = await fn(response, request, opts); + } + } + + const result = { + request, + response, + }; + + if (response.ok) { + const parseAs = + (opts.parseAs === 'auto' + ? getParseAs(response.headers.get('Content-Type')) + : opts.parseAs) ?? 'json'; + + if (response.status === 204 || response.headers.get('Content-Length') === '0') { + let emptyData: any; + switch (parseAs) { + case 'arrayBuffer': + case 'blob': + case 'text': + emptyData = await response[parseAs](); + break; + case 'formData': + emptyData = new FormData(); + break; + case 'stream': + emptyData = response.body; + break; + case 'json': + default: + emptyData = {}; + break; + } + return opts.responseStyle === 'data' + ? emptyData + : { + data: emptyData, + ...result, + }; + } + + let data: any; + switch (parseAs) { + case 'arrayBuffer': + case 'blob': + case 'formData': + case 'text': + data = await response[parseAs](); + break; + case 'json': { + // Some servers return 200 with no Content-Length and empty body. + // response.json() would throw; read as text and parse if non-empty. + const text = await response.text(); + data = text ? JSON.parse(text) : {}; + break; + } + case 'stream': + return opts.responseStyle === 'data' + ? response.body + : { + data: response.body, + ...result, + }; + } + + if (parseAs === 'json') { + if (opts.responseValidator) { + await opts.responseValidator(data); + } + + if (opts.responseTransformer) { + data = await opts.responseTransformer(data); + } + } + + return opts.responseStyle === 'data' + ? data + : { + data, + ...result, + }; + } + + const textError = await response.text(); + let jsonError: unknown; + + try { + jsonError = JSON.parse(textError); + } catch { + // noop + } + + const error = jsonError ?? textError; + let finalError = error; + + for (const fn of interceptors.error.fns) { + if (fn) { + finalError = (await fn(error, response, request, opts)) as string; + } + } + + finalError = finalError || ({} as string); + + if (opts.throwOnError) { + throw finalError; + } + + // TODO: we probably want to return error and improve types + return opts.responseStyle === 'data' + ? undefined + : { + error: finalError, + ...result, + }; + }; + + const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => + request({ ...options, method }); + + const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { + const { opts, url } = await beforeRequest(options); + return createSseClient({ + ...opts, + body: opts.body as BodyInit | null | undefined, + headers: opts.headers as unknown as Record, + method, + onRequest: async (url, init) => { + let request = new Request(url, init); + for (const fn of interceptors.request.fns) { + if (fn) { + request = await fn(request, opts); + } + } + return request; + }, + serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, + url, + }); + }; + + const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); + + return { + buildUrl: _buildUrl, + connect: makeMethodFn('CONNECT'), + delete: makeMethodFn('DELETE'), + get: makeMethodFn('GET'), + getConfig, + head: makeMethodFn('HEAD'), + interceptors, + options: makeMethodFn('OPTIONS'), + patch: makeMethodFn('PATCH'), + post: makeMethodFn('POST'), + put: makeMethodFn('PUT'), + request, + setConfig, + sse: { + connect: makeSseFn('CONNECT'), + delete: makeSseFn('DELETE'), + get: makeSseFn('GET'), + head: makeSseFn('HEAD'), + options: makeSseFn('OPTIONS'), + patch: makeSseFn('PATCH'), + post: makeSseFn('POST'), + put: makeSseFn('PUT'), + trace: makeSseFn('TRACE'), + }, + trace: makeMethodFn('TRACE'), + } as Client; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/client/index.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/client/index.ts new file mode 100644 index 0000000000..b295edeca0 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/client/index.ts @@ -0,0 +1,25 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type { Auth } from '../core/auth.gen'; +export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; +export { + formDataBodySerializer, + jsonBodySerializer, + urlSearchParamsBodySerializer, +} from '../core/bodySerializer.gen'; +export { buildClientParams } from '../core/params.gen'; +export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; +export { createClient } from './client.gen'; +export type { + Client, + ClientOptions, + Config, + CreateClientConfig, + Options, + RequestOptions, + RequestResult, + ResolvedRequestOptions, + ResponseStyle, + TDataShape, +} from './types.gen'; +export { createConfig, mergeHeaders } from './utils.gen'; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/client/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/client/types.gen.ts new file mode 100644 index 0000000000..a3f8616511 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/client/types.gen.ts @@ -0,0 +1,214 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Auth } from '../core/auth.gen'; +import type { + ServerSentEventsOptions, + ServerSentEventsResult, +} from '../core/serverSentEvents.gen'; +import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; +import type { Middleware } from './utils.gen'; + +export type ResponseStyle = 'data' | 'fields'; + +export interface Config + extends Omit, CoreConfig { + /** + * Base URL for all requests made by this client. + */ + baseUrl?: T['baseUrl']; + /** + * Fetch API implementation. You can use this option to provide a custom + * fetch instance. + * + * @default globalThis.fetch + */ + fetch?: typeof fetch; + /** + * Please don't use the Fetch client for Next.js applications. The `next` + * options won't have any effect. + * + * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. + */ + next?: never; + /** + * Return the response data parsed in a specified format. By default, `auto` + * will infer the appropriate method from the `Content-Type` response header. + * You can override this behavior with any of the {@link Body} methods. + * Select `stream` if you don't want to parse response data at all. + * + * @default 'auto' + */ + parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; + /** + * Should we return only data or multiple fields (data, error, response, etc.)? + * + * @default 'fields' + */ + responseStyle?: ResponseStyle; + /** + * Throw an error instead of returning it in the response? + * + * @default false + */ + throwOnError?: T['throwOnError']; +} + +export interface RequestOptions< + TData = unknown, + TResponseStyle extends ResponseStyle = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, +> + extends + Config<{ + responseStyle: TResponseStyle; + throwOnError: ThrowOnError; + }>, + Pick< + ServerSentEventsOptions, + | 'onRequest' + | 'onSseError' + | 'onSseEvent' + | 'sseDefaultRetryDelay' + | 'sseMaxRetryAttempts' + | 'sseMaxRetryDelay' + > { + /** + * Any body that you want to add to your request. + * + * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} + */ + body?: unknown; + path?: Record; + query?: Record; + /** + * Security mechanism(s) to use for the request. + */ + security?: ReadonlyArray; + url: Url; +} + +export interface ResolvedRequestOptions< + TResponseStyle extends ResponseStyle = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, +> extends RequestOptions { + serializedBody?: string; +} + +export type RequestResult< + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = boolean, + TResponseStyle extends ResponseStyle = 'fields', +> = ThrowOnError extends true + ? Promise< + TResponseStyle extends 'data' + ? TData extends Record + ? TData[keyof TData] + : TData + : { + data: TData extends Record ? TData[keyof TData] : TData; + request: Request; + response: Response; + } + > + : Promise< + TResponseStyle extends 'data' + ? (TData extends Record ? TData[keyof TData] : TData) | undefined + : ( + | { + data: TData extends Record ? TData[keyof TData] : TData; + error: undefined; + } + | { + data: undefined; + error: TError extends Record ? TError[keyof TError] : TError; + } + ) & { + request: Request; + response: Response; + } + >; + +export interface ClientOptions { + baseUrl?: string; + responseStyle?: ResponseStyle; + throwOnError?: boolean; +} + +type MethodFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'>, +) => RequestResult; + +type SseFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'>, +) => Promise>; + +type RequestFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'> & + Pick>, 'method'>, +) => RequestResult; + +type BuildUrlFn = < + TData extends { + body?: unknown; + path?: Record; + query?: Record; + url: string; + }, +>( + options: TData & Options, +) => string; + +export type Client = CoreClient & { + interceptors: Middleware; +}; + +/** + * The `createClientConfig()` function will be called on client initialization + * and the returned object will become the client's initial configuration. + * + * You may want to initialize your client this way instead of calling + * `setConfig()`. This is useful for example if you're using Next.js + * to ensure your client always has the correct values. + */ +export type CreateClientConfig = ( + override?: Config, +) => Config & T>; + +export interface TDataShape { + body?: unknown; + headers?: unknown; + path?: unknown; + query?: unknown; + url: string; +} + +type OmitKeys = Pick>; + +export type Options< + TData extends TDataShape = TDataShape, + ThrowOnError extends boolean = boolean, + TResponse = unknown, + TResponseStyle extends ResponseStyle = 'fields', +> = OmitKeys< + RequestOptions, + 'body' | 'path' | 'query' | 'url' +> & + ([TData] extends [never] ? unknown : Omit); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/client/utils.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/client/utils.gen.ts new file mode 100644 index 0000000000..b4bd2435ce --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/client/utils.gen.ts @@ -0,0 +1,316 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { getAuthToken } from '../core/auth.gen'; +import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; +import { jsonBodySerializer } from '../core/bodySerializer.gen'; +import { + serializeArrayParam, + serializeObjectParam, + serializePrimitiveParam, +} from '../core/pathSerializer.gen'; +import { getUrl } from '../core/utils.gen'; +import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; + +export const createQuerySerializer = ({ + parameters = {}, + ...args +}: QuerySerializerOptions = {}) => { + const querySerializer = (queryParams: T) => { + const search: string[] = []; + if (queryParams && typeof queryParams === 'object') { + for (const name in queryParams) { + const value = queryParams[name]; + + if (value === undefined || value === null) { + continue; + } + + const options = parameters[name] || args; + + if (Array.isArray(value)) { + const serializedArray = serializeArrayParam({ + allowReserved: options.allowReserved, + explode: true, + name, + style: 'form', + value, + ...options.array, + }); + if (serializedArray) search.push(serializedArray); + } else if (typeof value === 'object') { + const serializedObject = serializeObjectParam({ + allowReserved: options.allowReserved, + explode: true, + name, + style: 'deepObject', + value: value as Record, + ...options.object, + }); + if (serializedObject) search.push(serializedObject); + } else { + const serializedPrimitive = serializePrimitiveParam({ + allowReserved: options.allowReserved, + name, + value: value as string, + }); + if (serializedPrimitive) search.push(serializedPrimitive); + } + } + } + return search.join('&'); + }; + return querySerializer; +}; + +/** + * Infers parseAs value from provided Content-Type header. + */ +export const getParseAs = (contentType: string | null): Exclude => { + if (!contentType) { + // If no Content-Type header is provided, the best we can do is return the raw response body, + // which is effectively the same as the 'stream' option. + return 'stream'; + } + + const cleanContent = contentType.split(';')[0]?.trim(); + + if (!cleanContent) { + return; + } + + if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { + return 'json'; + } + + if (cleanContent === 'multipart/form-data') { + return 'formData'; + } + + if ( + ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) + ) { + return 'blob'; + } + + if (cleanContent.startsWith('text/')) { + return 'text'; + } + + return; +}; + +const checkForExistence = ( + options: Pick & { + headers: Headers; + }, + name?: string, +): boolean => { + if (!name) { + return false; + } + if ( + options.headers.has(name) || + options.query?.[name] || + options.headers.get('Cookie')?.includes(`${name}=`) + ) { + return true; + } + return false; +}; + +export const setAuthParams = async ({ + security, + ...options +}: Pick, 'security'> & + Pick & { + headers: Headers; + }) => { + for (const auth of security) { + if (checkForExistence(options, auth.name)) { + continue; + } + + const token = await getAuthToken(auth, options.auth); + + if (!token) { + continue; + } + + const name = auth.name ?? 'Authorization'; + + switch (auth.in) { + case 'query': + if (!options.query) { + options.query = {}; + } + options.query[name] = token; + break; + case 'cookie': + options.headers.append('Cookie', `${name}=${token}`); + break; + case 'header': + default: + options.headers.set(name, token); + break; + } + } +}; + +export const buildUrl: Client['buildUrl'] = (options) => + getUrl({ + baseUrl: options.baseUrl as string, + path: options.path, + query: options.query, + querySerializer: + typeof options.querySerializer === 'function' + ? options.querySerializer + : createQuerySerializer(options.querySerializer), + url: options.url, + }); + +export const mergeConfigs = (a: Config, b: Config): Config => { + const config = { ...a, ...b }; + if (config.baseUrl?.endsWith('/')) { + config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); + } + config.headers = mergeHeaders(a.headers, b.headers); + return config; +}; + +const headersEntries = (headers: Headers): Array<[string, string]> => { + const entries: Array<[string, string]> = []; + headers.forEach((value, key) => { + entries.push([key, value]); + }); + return entries; +}; + +export const mergeHeaders = ( + ...headers: Array['headers'] | undefined> +): Headers => { + const mergedHeaders = new Headers(); + for (const header of headers) { + if (!header) { + continue; + } + + const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); + + for (const [key, value] of iterator) { + if (value === null) { + mergedHeaders.delete(key); + } else if (Array.isArray(value)) { + for (const v of value) { + mergedHeaders.append(key, v as string); + } + } else if (value !== undefined) { + // assume object headers are meant to be JSON stringified, i.e. their + // content value in OpenAPI specification is 'application/json' + mergedHeaders.set( + key, + typeof value === 'object' ? JSON.stringify(value) : (value as string), + ); + } + } + } + return mergedHeaders; +}; + +type ErrInterceptor = ( + error: Err, + response: Res, + request: Req, + options: Options, +) => Err | Promise; + +type ReqInterceptor = (request: Req, options: Options) => Req | Promise; + +type ResInterceptor = ( + response: Res, + request: Req, + options: Options, +) => Res | Promise; + +class Interceptors { + fns: Array = []; + + clear(): void { + this.fns = []; + } + + eject(id: number | Interceptor): void { + const index = this.getInterceptorIndex(id); + if (this.fns[index]) { + this.fns[index] = null; + } + } + + exists(id: number | Interceptor): boolean { + const index = this.getInterceptorIndex(id); + return Boolean(this.fns[index]); + } + + getInterceptorIndex(id: number | Interceptor): number { + if (typeof id === 'number') { + return this.fns[id] ? id : -1; + } + return this.fns.indexOf(id); + } + + update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { + const index = this.getInterceptorIndex(id); + if (this.fns[index]) { + this.fns[index] = fn; + return id; + } + return false; + } + + use(fn: Interceptor): number { + this.fns.push(fn); + return this.fns.length - 1; + } +} + +export interface Middleware { + error: Interceptors>; + request: Interceptors>; + response: Interceptors>; +} + +export const createInterceptors = (): Middleware< + Req, + Res, + Err, + Options +> => ({ + error: new Interceptors>(), + request: new Interceptors>(), + response: new Interceptors>(), +}); + +const defaultQuerySerializer = createQuerySerializer({ + allowReserved: false, + array: { + explode: true, + style: 'form', + }, + object: { + explode: true, + style: 'deepObject', + }, +}); + +const defaultHeaders = { + 'Content-Type': 'application/json', +}; + +export const createConfig = ( + override: Config & T> = {}, +): Config & T> => ({ + ...jsonBodySerializer, + headers: defaultHeaders, + parseAs: 'auto', + querySerializer: defaultQuerySerializer, + ...override, +}); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/auth.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/auth.gen.ts new file mode 100644 index 0000000000..3ebf994788 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/auth.gen.ts @@ -0,0 +1,41 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type AuthToken = string | undefined; + +export interface Auth { + /** + * Which part of the request do we use to send the auth? + * + * @default 'header' + */ + in?: 'header' | 'query' | 'cookie'; + /** + * Header or query parameter name. + * + * @default 'Authorization' + */ + name?: string; + scheme?: 'basic' | 'bearer'; + type: 'apiKey' | 'http'; +} + +export const getAuthToken = async ( + auth: Auth, + callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, +): Promise => { + const token = typeof callback === 'function' ? await callback(auth) : callback; + + if (!token) { + return; + } + + if (auth.scheme === 'bearer') { + return `Bearer ${token}`; + } + + if (auth.scheme === 'basic') { + return `Basic ${btoa(token)}`; + } + + return token; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/bodySerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/bodySerializer.gen.ts new file mode 100644 index 0000000000..67daca60f8 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/bodySerializer.gen.ts @@ -0,0 +1,82 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; + +export type QuerySerializer = (query: Record) => string; + +export type BodySerializer = (body: unknown) => unknown; + +type QuerySerializerOptionsObject = { + allowReserved?: boolean; + array?: Partial>; + object?: Partial>; +}; + +export type QuerySerializerOptions = QuerySerializerOptionsObject & { + /** + * Per-parameter serialization overrides. When provided, these settings + * override the global array/object settings for specific parameter names. + */ + parameters?: Record; +}; + +const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { + if (typeof value === 'string' || value instanceof Blob) { + data.append(key, value); + } else if (value instanceof Date) { + data.append(key, value.toISOString()); + } else { + data.append(key, JSON.stringify(value)); + } +}; + +const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { + if (typeof value === 'string') { + data.append(key, value); + } else { + data.append(key, JSON.stringify(value)); + } +}; + +export const formDataBodySerializer = { + bodySerializer: (body: unknown): FormData => { + const data = new FormData(); + + Object.entries(body as Record).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + if (Array.isArray(value)) { + value.forEach((v) => serializeFormDataPair(data, key, v)); + } else { + serializeFormDataPair(data, key, value); + } + }); + + return data; + }, +}; + +export const jsonBodySerializer = { + bodySerializer: (body: unknown): string => + JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), +}; + +export const urlSearchParamsBodySerializer = { + bodySerializer: (body: unknown): string => { + const data = new URLSearchParams(); + + Object.entries(body as Record).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + if (Array.isArray(value)) { + value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); + } else { + serializeUrlSearchParamsPair(data, key, value); + } + }); + + return data.toString(); + }, +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/params.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/params.gen.ts new file mode 100644 index 0000000000..7955601a5c --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/params.gen.ts @@ -0,0 +1,169 @@ +// This file is auto-generated by @hey-api/openapi-ts + +type Slot = 'body' | 'headers' | 'path' | 'query'; + +export type Field = + | { + in: Exclude; + /** + * Field name. This is the name we want the user to see and use. + */ + key: string; + /** + * Field mapped name. This is the name we want to use in the request. + * If omitted, we use the same value as `key`. + */ + map?: string; + } + | { + in: Extract; + /** + * Key isn't required for bodies. + */ + key?: string; + map?: string; + } + | { + /** + * Field name. This is the name we want the user to see and use. + */ + key: string; + /** + * Field mapped name. This is the name we want to use in the request. + * If `in` is omitted, `map` aliases `key` to the transport layer. + */ + map: Slot; + }; + +export interface Fields { + allowExtra?: Partial>; + args?: ReadonlyArray; +} + +export type FieldsConfig = ReadonlyArray; + +const extraPrefixesMap: Record = { + $body_: 'body', + $headers_: 'headers', + $path_: 'path', + $query_: 'query', +}; +const extraPrefixes = Object.entries(extraPrefixesMap); + +type KeyMap = Map< + string, + | { + in: Slot; + map?: string; + } + | { + in?: never; + map: Slot; + } +>; + +const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { + if (!map) { + map = new Map(); + } + + for (const config of fields) { + if ('in' in config) { + if (config.key) { + map.set(config.key, { + in: config.in, + map: config.map, + }); + } + } else if ('key' in config) { + map.set(config.key, { + map: config.map, + }); + } else if (config.args) { + buildKeyMap(config.args, map); + } + } + + return map; +}; + +interface Params { + body: unknown; + headers: Record; + path: Record; + query: Record; +} + +const stripEmptySlots = (params: Params) => { + for (const [slot, value] of Object.entries(params)) { + if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { + delete params[slot as Slot]; + } + } +}; + +export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { + const params: Params = { + body: {}, + headers: {}, + path: {}, + query: {}, + }; + + const map = buildKeyMap(fields); + + let config: FieldsConfig[number] | undefined; + + for (const [index, arg] of args.entries()) { + if (fields[index]) { + config = fields[index]; + } + + if (!config) { + continue; + } + + if ('in' in config) { + if (config.key) { + const field = map.get(config.key)!; + const name = field.map || config.key; + if (field.in) { + (params[field.in] as Record)[name] = arg; + } + } else { + params.body = arg; + } + } else { + for (const [key, value] of Object.entries(arg ?? {})) { + const field = map.get(key); + + if (field) { + if (field.in) { + const name = field.map || key; + (params[field.in] as Record)[name] = value; + } else { + params[field.map] = value; + } + } else { + const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); + + if (extra) { + const [prefix, slot] = extra; + (params[slot] as Record)[key.slice(prefix.length)] = value; + } else if ('allowExtra' in config && config.allowExtra) { + for (const [slot, allowed] of Object.entries(config.allowExtra)) { + if (allowed) { + (params[slot as Slot] as Record)[key] = value; + break; + } + } + } + } + } + } + } + + stripEmptySlots(params); + + return params; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/pathSerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/pathSerializer.gen.ts new file mode 100644 index 0000000000..994b2848c6 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/pathSerializer.gen.ts @@ -0,0 +1,171 @@ +// This file is auto-generated by @hey-api/openapi-ts + +interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} + +interface SerializePrimitiveOptions { + allowReserved?: boolean; + name: string; +} + +export interface SerializerOptions { + /** + * @default true + */ + explode: boolean; + style: T; +} + +export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; +export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; +type MatrixStyle = 'label' | 'matrix' | 'simple'; +export type ObjectStyle = 'form' | 'deepObject'; +type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; + +interface SerializePrimitiveParam extends SerializePrimitiveOptions { + value: string; +} + +export const separatorArrayExplode = (style: ArraySeparatorStyle) => { + switch (style) { + case 'label': + return '.'; + case 'matrix': + return ';'; + case 'simple': + return ','; + default: + return '&'; + } +}; + +export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { + switch (style) { + case 'form': + return ','; + case 'pipeDelimited': + return '|'; + case 'spaceDelimited': + return '%20'; + default: + return ','; + } +}; + +export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { + switch (style) { + case 'label': + return '.'; + case 'matrix': + return ';'; + case 'simple': + return ','; + default: + return '&'; + } +}; + +export const serializeArrayParam = ({ + allowReserved, + explode, + name, + style, + value, +}: SerializeOptions & { + value: unknown[]; +}) => { + if (!explode) { + const joinedValues = ( + allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) + ).join(separatorArrayNoExplode(style)); + switch (style) { + case 'label': + return `.${joinedValues}`; + case 'matrix': + return `;${name}=${joinedValues}`; + case 'simple': + return joinedValues; + default: + return `${name}=${joinedValues}`; + } + } + + const separator = separatorArrayExplode(style); + const joinedValues = value + .map((v) => { + if (style === 'label' || style === 'simple') { + return allowReserved ? v : encodeURIComponent(v as string); + } + + return serializePrimitiveParam({ + allowReserved, + name, + value: v as string, + }); + }) + .join(separator); + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; +}; + +export const serializePrimitiveParam = ({ + allowReserved, + name, + value, +}: SerializePrimitiveParam) => { + if (value === undefined || value === null) { + return ''; + } + + if (typeof value === 'object') { + throw new Error( + 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', + ); + } + + return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; +}; + +export const serializeObjectParam = ({ + allowReserved, + explode, + name, + style, + value, + valueOnly, +}: SerializeOptions & { + value: Record | Date; + valueOnly?: boolean; +}) => { + if (value instanceof Date) { + return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; + } + + if (style !== 'deepObject' && !explode) { + let values: string[] = []; + Object.entries(value).forEach(([key, v]) => { + values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; + }); + const joinedValues = values.join(','); + switch (style) { + case 'form': + return `${name}=${joinedValues}`; + case 'label': + return `.${joinedValues}`; + case 'matrix': + return `;${name}=${joinedValues}`; + default: + return joinedValues; + } + } + + const separator = separatorObjectExplode(style); + const joinedValues = Object.entries(value) + .map(([key, v]) => + serializePrimitiveParam({ + allowReserved, + name: style === 'deepObject' ? `${name}[${key}]` : key, + value: v as string, + }), + ) + .join(separator); + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/queryKeySerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/queryKeySerializer.gen.ts new file mode 100644 index 0000000000..5000df606f --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/queryKeySerializer.gen.ts @@ -0,0 +1,117 @@ +// This file is auto-generated by @hey-api/openapi-ts + +/** + * JSON-friendly union that mirrors what Pinia Colada can hash. + */ +export type JsonValue = + | null + | string + | number + | boolean + | JsonValue[] + | { [key: string]: JsonValue }; + +/** + * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. + */ +export const queryKeyJsonReplacer = (_key: string, value: unknown) => { + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { + return undefined; + } + if (typeof value === 'bigint') { + return value.toString(); + } + if (value instanceof Date) { + return value.toISOString(); + } + return value; +}; + +/** + * Safely stringifies a value and parses it back into a JsonValue. + */ +export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { + try { + const json = JSON.stringify(input, queryKeyJsonReplacer); + if (json === undefined) { + return undefined; + } + return JSON.parse(json) as JsonValue; + } catch { + return undefined; + } +}; + +/** + * Detects plain objects (including objects with a null prototype). + */ +const isPlainObject = (value: unknown): value is Record => { + if (value === null || typeof value !== 'object') { + return false; + } + const prototype = Object.getPrototypeOf(value as object); + return prototype === Object.prototype || prototype === null; +}; + +/** + * Turns URLSearchParams into a sorted JSON object for deterministic keys. + */ +const serializeSearchParams = (params: URLSearchParams): JsonValue => { + const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); + const result: Record = {}; + + for (const [key, value] of entries) { + const existing = result[key]; + if (existing === undefined) { + result[key] = value; + continue; + } + + if (Array.isArray(existing)) { + (existing as string[]).push(value); + } else { + result[key] = [existing, value]; + } + } + + return result; +}; + +/** + * Normalizes any accepted value into a JSON-friendly shape for query keys. + */ +export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { + if (value === null) { + return null; + } + + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return value; + } + + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { + return undefined; + } + + if (typeof value === 'bigint') { + return value.toString(); + } + + if (value instanceof Date) { + return value.toISOString(); + } + + if (Array.isArray(value)) { + return stringifyToJsonValue(value); + } + + if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { + return serializeSearchParams(value); + } + + if (isPlainObject(value)) { + return stringifyToJsonValue(value); + } + + return undefined; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/serverSentEvents.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/serverSentEvents.gen.ts new file mode 100644 index 0000000000..6aa6cf02a4 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/serverSentEvents.gen.ts @@ -0,0 +1,243 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Config } from './types.gen'; + +export type ServerSentEventsOptions = Omit & + Pick & { + /** + * Fetch API implementation. You can use this option to provide a custom + * fetch instance. + * + * @default globalThis.fetch + */ + fetch?: typeof fetch; + /** + * Implementing clients can call request interceptors inside this hook. + */ + onRequest?: (url: string, init: RequestInit) => Promise; + /** + * Callback invoked when a network or parsing error occurs during streaming. + * + * This option applies only if the endpoint returns a stream of events. + * + * @param error The error that occurred. + */ + onSseError?: (error: unknown) => void; + /** + * Callback invoked when an event is streamed from the server. + * + * This option applies only if the endpoint returns a stream of events. + * + * @param event Event streamed from the server. + * @returns Nothing (void). + */ + onSseEvent?: (event: StreamEvent) => void; + serializedBody?: RequestInit['body']; + /** + * Default retry delay in milliseconds. + * + * This option applies only if the endpoint returns a stream of events. + * + * @default 3000 + */ + sseDefaultRetryDelay?: number; + /** + * Maximum number of retry attempts before giving up. + */ + sseMaxRetryAttempts?: number; + /** + * Maximum retry delay in milliseconds. + * + * Applies only when exponential backoff is used. + * + * This option applies only if the endpoint returns a stream of events. + * + * @default 30000 + */ + sseMaxRetryDelay?: number; + /** + * Optional sleep function for retry backoff. + * + * Defaults to using `setTimeout`. + */ + sseSleepFn?: (ms: number) => Promise; + url: string; + }; + +export interface StreamEvent { + data: TData; + event?: string; + id?: string; + retry?: number; +} + +export type ServerSentEventsResult = { + stream: AsyncGenerator< + TData extends Record ? TData[keyof TData] : TData, + TReturn, + TNext + >; +}; + +export const createSseClient = ({ + onRequest, + onSseError, + onSseEvent, + responseTransformer, + responseValidator, + sseDefaultRetryDelay, + sseMaxRetryAttempts, + sseMaxRetryDelay, + sseSleepFn, + url, + ...options +}: ServerSentEventsOptions): ServerSentEventsResult => { + let lastEventId: string | undefined; + + const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + + const createStream = async function* () { + let retryDelay: number = sseDefaultRetryDelay ?? 3000; + let attempt = 0; + const signal = options.signal ?? new AbortController().signal; + + while (true) { + if (signal.aborted) break; + + attempt++; + + const headers = + options.headers instanceof Headers + ? options.headers + : new Headers(options.headers as Record | undefined); + + if (lastEventId !== undefined) { + headers.set('Last-Event-ID', lastEventId); + } + + try { + const requestInit: RequestInit = { + redirect: 'follow', + ...options, + body: options.serializedBody, + headers, + signal, + }; + let request = new Request(url, requestInit); + if (onRequest) { + request = await onRequest(url, requestInit); + } + // fetch must be assigned here, otherwise it would throw the error: + // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation + const _fetch = options.fetch ?? globalThis.fetch; + const response = await _fetch(request); + + if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); + + if (!response.body) throw new Error('No body in SSE response'); + + const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); + + let buffer = ''; + + const abortHandler = () => { + try { + reader.cancel(); + } catch { + // noop + } + }; + + signal.addEventListener('abort', abortHandler); + + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + buffer += value; + // Normalize line endings: CRLF -> LF, then CR -> LF + buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); + + const chunks = buffer.split('\n\n'); + buffer = chunks.pop() ?? ''; + + for (const chunk of chunks) { + const lines = chunk.split('\n'); + const dataLines: Array = []; + let eventName: string | undefined; + + for (const line of lines) { + if (line.startsWith('data:')) { + dataLines.push(line.replace(/^data:\s*/, '')); + } else if (line.startsWith('event:')) { + eventName = line.replace(/^event:\s*/, ''); + } else if (line.startsWith('id:')) { + lastEventId = line.replace(/^id:\s*/, ''); + } else if (line.startsWith('retry:')) { + const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); + if (!Number.isNaN(parsed)) { + retryDelay = parsed; + } + } + } + + let data: unknown; + let parsedJson = false; + + if (dataLines.length) { + const rawData = dataLines.join('\n'); + try { + data = JSON.parse(rawData); + parsedJson = true; + } catch { + data = rawData; + } + } + + if (parsedJson) { + if (responseValidator) { + await responseValidator(data); + } + + if (responseTransformer) { + data = await responseTransformer(data); + } + } + + onSseEvent?.({ + data, + event: eventName, + id: lastEventId, + retry: retryDelay, + }); + + if (dataLines.length) { + yield data as any; + } + } + } + } finally { + signal.removeEventListener('abort', abortHandler); + reader.releaseLock(); + } + + break; // exit loop on normal completion + } catch (error) { + // connection failed or aborted; retry after delay + onSseError?.(error); + + if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { + break; // stop after firing error + } + + // exponential backoff: double retry each attempt, cap at 30s + const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); + await sleep(backoff); + } + } + }; + + const stream = createStream(); + + return { stream }; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/types.gen.ts new file mode 100644 index 0000000000..97463257e4 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/types.gen.ts @@ -0,0 +1,104 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Auth, AuthToken } from './auth.gen'; +import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; + +export type HttpMethod = + | 'connect' + | 'delete' + | 'get' + | 'head' + | 'options' + | 'patch' + | 'post' + | 'put' + | 'trace'; + +export type Client< + RequestFn = never, + Config = unknown, + MethodFn = never, + BuildUrlFn = never, + SseFn = never, +> = { + /** + * Returns the final request URL. + */ + buildUrl: BuildUrlFn; + getConfig: () => Config; + request: RequestFn; + setConfig: (config: Config) => Config; +} & { + [K in HttpMethod]: MethodFn; +} & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); + +export interface Config { + /** + * Auth token or a function returning auth token. The resolved value will be + * added to the request payload as defined by its `security` array. + */ + auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; + /** + * A function for serializing request body parameter. By default, + * {@link JSON.stringify()} will be used. + */ + bodySerializer?: BodySerializer | null; + /** + * An object containing any HTTP headers that you want to pre-populate your + * `Headers` object with. + * + * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} + */ + headers?: + | RequestInit['headers'] + | Record< + string, + string | number | boolean | (string | number | boolean)[] | null | undefined | unknown + >; + /** + * The request method. + * + * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} + */ + method?: Uppercase; + /** + * A function for serializing request query parameters. By default, arrays + * will be exploded in form style, objects will be exploded in deepObject + * style, and reserved characters are percent-encoded. + * + * This method will have no effect if the native `paramsSerializer()` Axios + * API function is used. + * + * {@link https://swagger.io/docs/specification/serialization/#query View examples} + */ + querySerializer?: QuerySerializer | QuerySerializerOptions; + /** + * A function validating request data. This is useful if you want to ensure + * the request conforms to the desired shape, so it can be safely sent to + * the server. + */ + requestValidator?: (data: unknown) => Promise; + /** + * A function transforming response data before it's returned. This is useful + * for post-processing data, e.g. converting ISO strings into Date objects. + */ + responseTransformer?: (data: unknown) => Promise; + /** + * A function validating response data. This is useful if you want to ensure + * the response conforms to the desired shape, so it can be safely passed to + * the transformers and returned to the user. + */ + responseValidator?: (data: unknown) => Promise; +} + +type IsExactlyNeverOrNeverUndefined = [T] extends [never] + ? true + : [T] extends [never | undefined] + ? [undefined] extends [T] + ? false + : true + : false; + +export type OmitNever> = { + [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/utils.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/utils.gen.ts new file mode 100644 index 0000000000..e7ddbe3541 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/core/utils.gen.ts @@ -0,0 +1,140 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; +import { + type ArraySeparatorStyle, + serializeArrayParam, + serializeObjectParam, + serializePrimitiveParam, +} from './pathSerializer.gen'; + +export interface PathSerializer { + path: Record; + url: string; +} + +export const PATH_PARAM_RE = /\{[^{}]+\}/g; + +export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { + let url = _url; + const matches = _url.match(PATH_PARAM_RE); + if (matches) { + for (const match of matches) { + let explode = false; + let name = match.substring(1, match.length - 1); + let style: ArraySeparatorStyle = 'simple'; + + if (name.endsWith('*')) { + explode = true; + name = name.substring(0, name.length - 1); + } + + if (name.startsWith('.')) { + name = name.substring(1); + style = 'label'; + } else if (name.startsWith(';')) { + name = name.substring(1); + style = 'matrix'; + } + + const value = path[name]; + + if (value === undefined || value === null) { + continue; + } + + if (Array.isArray(value)) { + url = url.replace(match, serializeArrayParam({ explode, name, style, value })); + continue; + } + + if (typeof value === 'object') { + url = url.replace( + match, + serializeObjectParam({ + explode, + name, + style, + value: value as Record, + valueOnly: true, + }), + ); + continue; + } + + if (style === 'matrix') { + url = url.replace( + match, + `;${serializePrimitiveParam({ + name, + value: value as string, + })}`, + ); + continue; + } + + const replaceValue = encodeURIComponent( + style === 'label' ? `.${value as string}` : (value as string), + ); + url = url.replace(match, replaceValue); + } + } + return url; +}; + +export const getUrl = ({ + baseUrl, + path, + query, + querySerializer, + url: _url, +}: { + baseUrl?: string; + path?: Record; + query?: Record; + querySerializer: QuerySerializer; + url: string; +}) => { + const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; + let url = (baseUrl ?? '') + pathUrl; + if (path) { + url = defaultPathSerializer({ path, url }); + } + let search = query ? querySerializer(query) : ''; + if (search.startsWith('?')) { + search = search.substring(1); + } + if (search) { + url += `?${search}`; + } + return url; +}; + +export function getValidRequestBody(options: { + body?: unknown; + bodySerializer?: BodySerializer | null; + serializedBody?: unknown; +}) { + const hasBody = options.body !== undefined; + const isSerializedBody = hasBody && options.bodySerializer; + + if (isSerializedBody) { + if ('serializedBody' in options) { + const hasSerializedBody = + options.serializedBody !== undefined && options.serializedBody !== ''; + + return hasSerializedBody ? options.serializedBody : null; + } + + // not all clients implement a serializedBody property (i.e. client-axios) + return options.body !== '' ? options.body : null; + } + + // plain/text body + if (hasBody) { + return options.body; + } + + // no body was provided + return undefined; +} diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/index.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/index.ts new file mode 100644 index 0000000000..6e132194fd --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/index.ts @@ -0,0 +1,4 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; +export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/sdk.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/sdk.gen.ts new file mode 100644 index 0000000000..e48dcff8cf --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/sdk.gen.ts @@ -0,0 +1,206 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; +import { client } from './client.gen'; +import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; + +export type Options = Options2 & { + /** + * You can provide a client instance returned by `createClient()` instead of + * individual options. This might be also useful if you want to implement a + * custom client. + */ + client?: Client; + /** + * You can pass arbitrary values through the `meta` object. This can be + * used to access values that aren't defined as part of the SDK function. + */ + meta?: Record; +}; + +export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); + +export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); + +export const import_ = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/no+tag', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); + +export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); + +export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); + +export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); + +export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); + +export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); + +export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); + +export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); + +export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); + +export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); + +export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); + +export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); + +/** + * @deprecated + */ +export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); + +export const callWithParameters = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/parameters/{parameterPath}', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ + url: '/api/v{api-version}/parameters', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/parameters', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ + url: '/api/v{api-version}/requestBody', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options?.headers + } +}); + +export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ + ...formDataBodySerializer, + url: '/api/v{api-version}/formData', + ...options, + headers: { + 'Content-Type': null, + ...options?.headers + } +}); + +export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); + +export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); + +export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); + +export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); + +export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); + +export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); + +export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); + +export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); + +export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); + +export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); + +export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); + +export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); + +export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); + +export const uploadFile = (options: Options) => (options.client ?? client).post({ + ...urlSearchParamsBodySerializer, + url: '/api/v{api-version}/upload', + ...options, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + ...options.headers + } +}); + +export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); + +export const complexTypes = (options: Options) => (options.client ?? client).get({ + querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, + url: '/api/v{api-version}/complex', + ...options +}); + +export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); + +export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ + ...formDataBodySerializer, + url: '/api/v{api-version}/multipart', + ...options, + headers: { + 'Content-Type': null, + ...options?.headers + } +}); + +export const complexParams = (options: Options) => (options.client ?? client).put({ + url: '/api/v{api-version}/complex/{id}', + ...options, + headers: { + 'Content-Type': 'application/json-patch+json', + ...options.headers + } +}); + +export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); + +export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); + +export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); + +/** + * Login User + */ +export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ + ...urlSearchParamsBodySerializer, + url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', + ...options, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + ...options.headers + } +}); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/types.gen.ts new file mode 100644 index 0000000000..d819316644 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery-disabled/types.gen.ts @@ -0,0 +1,2100 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type ClientOptions = { + baseUrl: 'http://localhost:3000/base' | (string & {}); +}; + +/** + * Model with number-only name + */ +export type _400 = string; + +/** + * External ref to shared model (A) + */ +export type ExternalRefA = ExternalSharedModel; + +/** + * External ref to shared model (B) + */ +export type ExternalRefB = ExternalSharedModel; + +/** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ +export type CamelCaseCommentWithBreaks = number; + +/** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ +export type CommentWithBreaks = number; + +/** + * Testing backticks in string: `backticks` and ```multiple backticks``` should work + */ +export type CommentWithBackticks = number; + +/** + * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work + */ +export type CommentWithBackticksAndQuotes = number; + +/** + * Testing slashes in string: \backwards\\\ and /forwards/// should work + */ +export type CommentWithSlashes = number; + +/** + * Testing expression placeholders in string: ${expression} should work + */ +export type CommentWithExpressionPlaceholders = number; + +/** + * Testing quotes in string: 'single quote''' and "double quotes""" should work + */ +export type CommentWithQuotes = number; + +/** + * Testing reserved characters in string: * inline * and ** inline ** should work + */ +export type CommentWithReservedCharacters = number; + +/** + * This is a simple number + */ +export type SimpleInteger = number; + +/** + * This is a simple boolean + */ +export type SimpleBoolean = boolean; + +/** + * This is a simple string + */ +export type SimpleString = string; + +/** + * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) + */ +export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; + +/** + * This is a simple file + */ +export type SimpleFile = Blob | File; + +/** + * This is a simple reference + */ +export type SimpleReference = ModelWithString; + +/** + * This is a simple string + */ +export type SimpleStringWithPattern = string | null; + +/** + * This is a simple enum with strings + */ +export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; + +export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; + +/** + * This is a simple enum with numbers + */ +export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; + +/** + * Success=1,Warning=2,Error=3 + */ +export type EnumFromDescription = number; + +/** + * This is a simple enum with numbers + */ +export type EnumWithExtensions = 200 | 400 | 500; + +export type EnumWithXEnumNames = 0 | 1 | 2; + +/** + * This is a simple array with numbers + */ +export type ArrayWithNumbers = Array; + +/** + * This is a simple array with booleans + */ +export type ArrayWithBooleans = Array; + +/** + * This is a simple array with strings + */ +export type ArrayWithStrings = Array; + +/** + * This is a simple array with references + */ +export type ArrayWithReferences = Array; + +/** + * This is a simple array containing an array + */ +export type ArrayWithArray = Array>; + +/** + * This is a simple array with properties + */ +export type ArrayWithProperties = Array<{ + '16x16'?: CamelCaseCommentWithBreaks; + bar?: string; +}>; + +/** + * This is a simple array with any of properties + */ +export type ArrayWithAnyOfProperties = Array<{ + foo?: string; +} | { + bar?: string; +}>; + +export type AnyOfAnyAndNull = { + data?: unknown | null; +}; + +/** + * This is a simple array with any of properties + */ +export type AnyOfArrays = { + results?: Array<{ + foo?: string; + } | { + bar?: string; + }>; +}; + +/** + * This is a string dictionary + */ +export type DictionaryWithString = { + [key: string]: string; +}; + +export type DictionaryWithPropertiesAndAdditionalProperties = { + foo?: number; + bar?: boolean; + [key: string]: string | number | boolean | undefined; +}; + +/** + * This is a string reference + */ +export type DictionaryWithReference = { + [key: string]: ModelWithString; +}; + +/** + * This is a complex dictionary + */ +export type DictionaryWithArray = { + [key: string]: Array; +}; + +/** + * This is a string dictionary + */ +export type DictionaryWithDictionary = { + [key: string]: { + [key: string]: string; + }; +}; + +/** + * This is a complex dictionary + */ +export type DictionaryWithProperties = { + [key: string]: { + foo?: string; + bar?: string; + }; +}; + +/** + * This is a model with one number property + */ +export type ModelWithInteger = { + /** + * This is a simple number property + */ + prop?: number; +}; + +/** + * This is a model with one boolean property + */ +export type ModelWithBoolean = { + /** + * This is a simple boolean property + */ + prop?: boolean; +}; + +/** + * This is a model with one string property + */ +export type ModelWithString = { + /** + * This is a simple string property + */ + prop?: string; +}; + +/** + * This is a model with one string property + */ +export type ModelWithStringError = { + /** + * This is a simple string property + */ + prop?: string; +}; + +/** + * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) + */ +export type ModelFromZendesk = string; + +/** + * This is a model with one string property + */ +export type ModelWithNullableString = { + /** + * This is a simple string property + */ + nullableProp1?: string | null; + /** + * This is a simple string property + */ + nullableRequiredProp1: string | null; + /** + * This is a simple string property + */ + nullableProp2?: string | null; + /** + * This is a simple string property + */ + nullableRequiredProp2: string | null; + /** + * This is a simple enum with strings + */ + 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; +}; + +/** + * This is a model with one enum + */ +export type ModelWithEnum = { + /** + * This is a simple enum with strings + */ + 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; + /** + * These are the HTTP error code enums + */ + statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; + /** + * Simple boolean enum + */ + bool?: true; +}; + +/** + * This is a model with one enum with escaped name + */ +export type ModelWithEnumWithHyphen = { + /** + * Foo-Bar-Baz-Qux + */ + 'foo-bar-baz-qux'?: '3.0'; +}; + +/** + * This is a model with one enum + */ +export type ModelWithEnumFromDescription = { + /** + * Success=1,Warning=2,Error=3 + */ + test?: number; +}; + +/** + * This is a model with nested enums + */ +export type ModelWithNestedEnums = { + dictionaryWithEnum?: { + [key: string]: 'Success' | 'Warning' | 'Error'; + }; + dictionaryWithEnumFromDescription?: { + [key: string]: number; + }; + arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; + arrayWithDescription?: Array; + /** + * This is a simple enum with strings + */ + 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; +}; + +/** + * This is a model with one property containing a reference + */ +export type ModelWithReference = { + prop?: ModelWithProperties; +}; + +/** + * This is a model with one property containing an array + */ +export type ModelWithArrayReadOnlyAndWriteOnly = { + prop?: Array; + propWithFile?: Array; + propWithNumber?: Array; +}; + +/** + * This is a model with one property containing an array + */ +export type ModelWithArray = { + prop?: Array; + propWithFile?: Array; + propWithNumber?: Array; +}; + +/** + * This is a model with one property containing a dictionary + */ +export type ModelWithDictionary = { + prop?: { + [key: string]: string; + }; +}; + +/** + * This is a deprecated model with a deprecated property + * + * @deprecated + */ +export type DeprecatedModel = { + /** + * This is a deprecated property + * + * @deprecated + */ + prop?: string; +}; + +/** + * This is a model with one property containing a circular reference + */ +export type ModelWithCircularReference = { + prop?: ModelWithCircularReference; +}; + +/** + * This is a model with one property with a 'one of' relationship + */ +export type CompositionWithOneOf = { + propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; +}; + +/** + * This is a model with one property with a 'one of' relationship where the options are not $ref + */ +export type CompositionWithOneOfAnonymous = { + propA?: { + propA?: string; + } | string | number; +}; + +/** + * Circle + */ +export type ModelCircle = { + kind: string; + radius?: number; +}; + +/** + * Square + */ +export type ModelSquare = { + kind: string; + sideLength?: number; +}; + +/** + * This is a model with one property with a 'one of' relationship where the options are not $ref + */ +export type CompositionWithOneOfDiscriminator = ({ + kind: 'circle'; +} & ModelCircle) | ({ + kind: 'square'; +} & ModelSquare); + +/** + * This is a model with one property with a 'any of' relationship + */ +export type CompositionWithAnyOf = { + propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; +}; + +/** + * This is a model with one property with a 'any of' relationship where the options are not $ref + */ +export type CompositionWithAnyOfAnonymous = { + propA?: { + propA?: string; + } | string | number; +}; + +/** + * This is a model with nested 'any of' property with a type null + */ +export type CompositionWithNestedAnyAndTypeNull = { + propA?: Array | Array; +}; + +export type _3eNum1Период = 'Bird' | 'Dog'; + +export type ConstValue = 'ConstValue'; + +/** + * This is a model with one property with a 'any of' relationship where the options are not $ref + */ +export type CompositionWithNestedAnyOfAndNull = { + /** + * Scopes + */ + propA?: Array<_3eNum1Период | ConstValue> | null; +}; + +/** + * This is a model with one property with a 'one of' relationship + */ +export type CompositionWithOneOfAndNullable = { + propA?: { + boolean?: boolean; + } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; +}; + +/** + * This is a model that contains a simple dictionary within composition + */ +export type CompositionWithOneOfAndSimpleDictionary = { + propA?: boolean | { + [key: string]: number; + }; +}; + +/** + * This is a model that contains a dictionary of simple arrays within composition + */ +export type CompositionWithOneOfAndSimpleArrayDictionary = { + propA?: boolean | { + [key: string]: Array; + }; +}; + +/** + * This is a model that contains a dictionary of complex arrays (composited) within composition + */ +export type CompositionWithOneOfAndComplexArrayDictionary = { + propA?: boolean | { + [key: string]: Array; + }; +}; + +/** + * This is a model with one property with a 'all of' relationship + */ +export type CompositionWithAllOfAndNullable = { + propA?: ({ + boolean?: boolean; + } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; +}; + +/** + * This is a model with one property with a 'any of' relationship + */ +export type CompositionWithAnyOfAndNullable = { + propA?: { + boolean?: boolean; + } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; +}; + +/** + * This is a base model with two simple optional properties + */ +export type CompositionBaseModel = { + firstName?: string; + lastname?: string; +}; + +/** + * This is a model that extends the base model + */ +export type CompositionExtendedModel = CompositionBaseModel & { + age: number; + firstName: string; + lastname: string; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithProperties = { + required: string; + readonly requiredAndReadOnly: string; + requiredAndNullable: string | null; + string?: string; + number?: number; + boolean?: boolean; + reference?: ModelWithString; + 'property with space'?: string; + default?: string; + try?: string; + readonly '@namespace.string'?: string; + readonly '@namespace.integer'?: number; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithNestedProperties = { + readonly first: { + readonly second: { + readonly third: string | null; + } | null; + } | null; +}; + +/** + * This is a model with duplicated properties + */ +export type ModelWithDuplicateProperties = { + prop?: ModelWithString; +}; + +/** + * This is a model with ordered properties + */ +export type ModelWithOrderedProperties = { + zebra?: string; + apple?: string; + hawaii?: string; +}; + +/** + * This is a model with duplicated imports + */ +export type ModelWithDuplicateImports = { + propA?: ModelWithString; + propB?: ModelWithString; + propC?: ModelWithString; +}; + +/** + * This is a model that extends another model + */ +export type ModelThatExtends = ModelWithString & { + propExtendsA?: string; + propExtendsB?: ModelWithString; +}; + +/** + * This is a model that extends another model + */ +export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { + propExtendsC?: string; + propExtendsD?: ModelWithString; +}; + +/** + * This is a model that contains a some patterns + */ +export type ModelWithPattern = { + key: string; + name: string; + readonly enabled?: boolean; + readonly modified?: string; + id?: string; + text?: string; + patternWithSingleQuotes?: string; + patternWithNewline?: string; + patternWithBacktick?: string; + patternWithUnicode?: string; +}; + +export type File = { + /** + * Id + */ + readonly id?: string; + /** + * Updated at + */ + readonly updated_at?: string; + /** + * Created at + */ + readonly created_at?: string; + /** + * Mime + */ + mime: string; + /** + * File + */ + readonly file?: string; +}; + +export type Default = { + name?: string; +}; + +export type Pageable = { + page?: number; + size?: number; + sort?: Array; +}; + +/** + * This is a free-form object without additionalProperties. + */ +export type FreeFormObjectWithoutAdditionalProperties = { + [key: string]: unknown; +}; + +/** + * This is a free-form object with additionalProperties: true. + */ +export type FreeFormObjectWithAdditionalPropertiesEqTrue = { + [key: string]: unknown; +}; + +/** + * This is a free-form object with additionalProperties: {}. + */ +export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { + [key: string]: unknown; +}; + +export type ModelWithConst = { + String?: 'String'; + number?: 0; + null?: null; + withType?: 'Some string'; +}; + +/** + * This is a model with one property and additionalProperties: true + */ +export type ModelWithAdditionalPropertiesEqTrue = { + /** + * This is a simple string property + */ + prop?: string; + [key: string]: unknown; +}; + +export type NestedAnyOfArraysNullable = { + nullableArray?: Array | null; +}; + +export type CompositionWithOneOfAndProperties = ({ + foo: SimpleParameter; +} | { + bar: NonAsciiStringæøåÆøÅöôêÊ字符串; +}) & { + baz: number | null; + qux: number; +}; + +/** + * An object that can be null + */ +export type NullableObject = { + foo?: string; +} | null; + +/** + * Some % character + */ +export type CharactersInDescription = string; + +export type ModelWithNullableObject = { + data?: NullableObject; +}; + +/** + * An object with additional properties that can be null (anyOf ref + null) + */ +export type ModelWithAdditionalPropertiesRef = { + [key: string]: NullableObject | null; +}; + +export type ModelWithOneOfEnum = { + foo: 'Bar'; +} | { + foo: 'Baz'; +} | { + foo: 'Qux'; +} | { + content: string; + foo: 'Quux'; +} | { + content: [ + string, + string + ]; + foo: 'Corge'; +}; + +export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; + +export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; + +export type ModelWithNestedArrayEnumsData = { + foo?: Array; + bar?: Array; +}; + +export type ModelWithNestedArrayEnums = { + array_strings?: Array; + data?: ModelWithNestedArrayEnumsData; +}; + +export type ModelWithNestedCompositionEnums = { + foo?: ModelWithNestedArrayEnumsDataFoo; +}; + +export type ModelWithReadOnlyAndWriteOnly = { + foo: string; + readonly bar: string; +}; + +export type ModelWithConstantSizeArray = [ + number, + number +]; + +export type ModelWithAnyOfConstantSizeArray = [ + number | string, + number | string, + number | string +]; + +export type ModelWithPrefixItemsConstantSizeArray = [ + ModelWithInteger, + number | string, + string +]; + +export type ModelWithAnyOfConstantSizeArrayNullable = [ + number | null | string, + number | null | string, + number | null | string +]; + +export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ + number | Import, + number | Import +]; + +export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ + number & string, + number & string +]; + +export type ModelWithNumericEnumUnion = { + /** + * Период + */ + value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; +}; + +/** + * Some description with `back ticks` + */ +export type ModelWithBackticksInDescription = { + /** + * The template `that` should be used for parsing and importing the contents of the CSV file. + * + *

There is one placeholder currently supported:

  • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

Example of a correct JSON template:

+ *
+     * [
+     * {
+     * "resourceType": "Asset",
+     * "identifier": {
+     * "name": "${1}",
+     * "domain": {
+     * "name": "${2}",
+     * "community": {
+     * "name": "Some Community"
+     * }
+     * }
+     * },
+     * "attributes" : {
+     * "00000000-0000-0000-0000-000000003115" : [ {
+     * "value" : "${3}"
+     * } ],
+     * "00000000-0000-0000-0000-000000000222" : [ {
+     * "value" : "${4}"
+     * } ]
+     * }
+     * }
+     * ]
+     * 
+ */ + template?: string; +}; + +export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { + baz: number | null; + qux: number; +}; + +/** + * Model used to test deduplication strategy (unused) + */ +export type ParameterSimpleParameterUnused = string; + +/** + * Model used to test deduplication strategy + */ +export type PostServiceWithEmptyTagResponse = string; + +/** + * Model used to test deduplication strategy + */ +export type PostServiceWithEmptyTagResponse2 = string; + +/** + * Model used to test deduplication strategy + */ +export type DeleteFooData = string; + +/** + * Model used to test deduplication strategy + */ +export type DeleteFooData2 = string; + +/** + * Model with restricted keyword name + */ +export type Import = string; + +export type SchemaWithFormRestrictedKeys = { + description?: string; + 'x-enum-descriptions'?: string; + 'x-enum-varnames'?: string; + 'x-enumNames'?: string; + title?: string; + object?: { + description?: string; + 'x-enum-descriptions'?: string; + 'x-enum-varnames'?: string; + 'x-enumNames'?: string; + title?: string; + }; + array?: Array<{ + description?: string; + 'x-enum-descriptions'?: string; + 'x-enum-varnames'?: string; + 'x-enumNames'?: string; + title?: string; + }>; +}; + +/** + * This schema was giving PascalCase transformations a hard time + */ +export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { + /** + * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. + */ + preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; +}; + +/** + * This schema was giving PascalCase transformations a hard time + */ +export type IoK8sApimachineryPkgApisMetaV1Preconditions = { + /** + * Specifies the target ResourceVersion + */ + resourceVersion?: string; + /** + * Specifies the target UID. + */ + uid?: string; +}; + +export type AdditionalPropertiesUnknownIssue = { + [key: string]: string | number; +}; + +export type AdditionalPropertiesUnknownIssue2 = { + [key: string]: string | number; +}; + +export type AdditionalPropertiesUnknownIssue3 = string & { + entries: { + [key: string]: AdditionalPropertiesUnknownIssue; + }; +}; + +export type AdditionalPropertiesIntegerIssue = { + value: number; + [key: string]: number; +}; + +export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; + +export type GenericSchemaDuplicateIssue1SystemBoolean = { + item?: boolean; + error?: string | null; + readonly hasError?: boolean; + data?: { + [key: string]: never; + }; +}; + +export type GenericSchemaDuplicateIssue1SystemString = { + item?: string | null; + error?: string | null; + readonly hasError?: boolean; +}; + +export type ExternalSharedModel = { + id: string; + name?: string; +}; + +/** + * This is a model with one property containing a reference + */ +export type ModelWithReferenceWritable = { + prop?: ModelWithPropertiesWritable; +}; + +/** + * This is a model with one property containing an array + */ +export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { + prop?: Array; + propWithFile?: Array; + propWithNumber?: Array; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithPropertiesWritable = { + required: string; + requiredAndNullable: string | null; + string?: string; + number?: number; + boolean?: boolean; + reference?: ModelWithString; + 'property with space'?: string; + default?: string; + try?: string; +}; + +/** + * This is a model that contains a some patterns + */ +export type ModelWithPatternWritable = { + key: string; + name: string; + id?: string; + text?: string; + patternWithSingleQuotes?: string; + patternWithNewline?: string; + patternWithBacktick?: string; + patternWithUnicode?: string; +}; + +export type FileWritable = { + /** + * Mime + */ + mime: string; +}; + +export type ModelWithReadOnlyAndWriteOnlyWritable = { + foo: string; + baz: string; +}; + +export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ + number | Import, + number | Import +]; + +export type AdditionalPropertiesUnknownIssueWritable = { + [key: string]: string | number; +}; + +export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; + +export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { + item?: boolean; + error?: string | null; + data?: { + [key: string]: never; + }; +}; + +export type GenericSchemaDuplicateIssue1SystemStringWritable = { + item?: string | null; + error?: string | null; +}; + +/** + * This is a reusable parameter + */ +export type SimpleParameter = string; + +/** + * Parameter with illegal characters + */ +export type XFooBar = ModelWithString; + +/** + * A reusable request body + */ +export type SimpleRequestBody = ModelWithString; + +/** + * A reusable request body + */ +export type SimpleFormData = ModelWithString; + +export type ExportData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type PatchApiVbyApiVersionNoTagData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type PatchApiVbyApiVersionNoTagResponses = { + /** + * OK + */ + default: unknown; +}; + +export type ImportData = { + body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type ImportResponses = { + /** + * Success + */ + 200: ModelFromZendesk; + /** + * Default success response + */ + default: ModelWithReadOnlyAndWriteOnly; +}; + +export type ImportResponse = ImportResponses[keyof ImportResponses]; + +export type FooWowData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type FooWowResponses = { + /** + * OK + */ + default: unknown; +}; + +export type ApiVVersionODataControllerCountData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple/$count'; +}; + +export type ApiVVersionODataControllerCountResponses = { + /** + * Success + */ + 200: ModelFromZendesk; +}; + +export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; + +export type GetApiVbyApiVersionSimpleOperationData = { + body?: never; + path: { + /** + * foo in method + */ + foo_param: string; + }; + query?: never; + url: '/api/v{api-version}/simple:operation'; +}; + +export type GetApiVbyApiVersionSimpleOperationErrors = { + /** + * Default error response + */ + default: ModelWithBoolean; +}; + +export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; + +export type GetApiVbyApiVersionSimpleOperationResponses = { + /** + * Response is a simple number + */ + 200: number; +}; + +export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; + +export type DeleteCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type GetCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type HeadCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type OptionsCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PatchCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PostCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PutCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type DeleteFooData3 = { + body?: never; + headers: { + /** + * Parameter with illegal characters + */ + 'x-Foo-Bar': ModelWithString; + }; + path: { + /** + * foo in method + */ + foo_param: string; + /** + * bar in method + */ + BarParam: string; + }; + query?: never; + url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; +}; + +export type CallWithDescriptionsData = { + body?: never; + path?: never; + query?: { + /** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ + parameterWithBreaks?: string; + /** + * Testing backticks in string: `backticks` and ```multiple backticks``` should work + */ + parameterWithBackticks?: string; + /** + * Testing slashes in string: \backwards\\\ and /forwards/// should work + */ + parameterWithSlashes?: string; + /** + * Testing expression placeholders in string: ${expression} should work + */ + parameterWithExpressionPlaceholders?: string; + /** + * Testing quotes in string: 'single quote''' and "double quotes""" should work + */ + parameterWithQuotes?: string; + /** + * Testing reserved characters in string: * inline * and ** inline ** should work + */ + parameterWithReservedCharacters?: string; + }; + url: '/api/v{api-version}/descriptions'; +}; + +export type DeprecatedCallData = { + body?: never; + headers: { + /** + * This parameter is deprecated + * + * @deprecated + */ + parameter: DeprecatedModel | null; + }; + path?: never; + query?: never; + url: '/api/v{api-version}/parameters/deprecated'; +}; + +export type CallWithParametersData = { + /** + * This is the parameter that goes into the body + */ + body: { + [key: string]: unknown; + } | null; + headers: { + /** + * This is the parameter that goes into the header + */ + parameterHeader: string | null; + }; + path: { + /** + * This is the parameter that goes into the path + */ + parameterPath: string | null; + /** + * api-version should be required in standalone clients + */ + 'api-version': string | null; + }; + query: { + foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; + foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; + /** + * This is the parameter that goes into the query params + */ + cursor: string | null; + }; + url: '/api/v{api-version}/parameters/{parameterPath}'; +}; + +export type CallWithWeirdParameterNamesData = { + /** + * This is the parameter that goes into the body + */ + body: ModelWithString | null; + headers: { + /** + * This is the parameter that goes into the request header + */ + 'parameter.header': string | null; + }; + path: { + /** + * This is the parameter that goes into the path + */ + 'parameter.path.1'?: string; + /** + * This is the parameter that goes into the path + */ + 'parameter-path-2'?: string; + /** + * This is the parameter that goes into the path + */ + 'PARAMETER-PATH-3'?: string; + /** + * api-version should be required in standalone clients + */ + 'api-version': string | null; + }; + query: { + /** + * This is the parameter with a reserved keyword + */ + default?: string; + /** + * This is the parameter that goes into the request query params + */ + 'parameter-query': string | null; + }; + url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; +}; + +export type GetCallWithOptionalParamData = { + /** + * This is a required parameter + */ + body: ModelWithOneOfEnum; + path?: never; + query?: { + /** + * This is an optional parameter + */ + page?: number; + }; + url: '/api/v{api-version}/parameters'; +}; + +export type PostCallWithOptionalParamData = { + /** + * This is an optional parameter + */ + body?: { + offset?: number | null; + }; + path?: never; + query: { + /** + * This is a required parameter + */ + parameter: Pageable; + }; + url: '/api/v{api-version}/parameters'; +}; + +export type PostCallWithOptionalParamResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Success + */ + 204: void; +}; + +export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; + +export type PostApiVbyApiVersionRequestBodyData = { + /** + * A reusable request body + */ + body?: SimpleRequestBody; + path?: never; + query?: { + /** + * This is a reusable parameter + */ + parameter?: string; + }; + url: '/api/v{api-version}/requestBody'; +}; + +export type PostApiVbyApiVersionFormDataData = { + /** + * A reusable request body + */ + body?: SimpleFormData; + path?: never; + query?: { + /** + * This is a reusable parameter + */ + parameter?: string; + }; + url: '/api/v{api-version}/formData'; +}; + +export type CallWithDefaultParametersData = { + body?: never; + path?: never; + query?: { + /** + * This is a simple string with default value + */ + parameterString?: string | null; + /** + * This is a simple number with default value + */ + parameterNumber?: number | null; + /** + * This is a simple boolean with default value + */ + parameterBoolean?: boolean | null; + /** + * This is a simple enum with default value + */ + parameterEnum?: 'Success' | 'Warning' | 'Error'; + /** + * This is a simple model with default value + */ + parameterModel?: ModelWithString | null; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type CallWithDefaultOptionalParametersData = { + body?: never; + path?: never; + query?: { + /** + * This is a simple string that is optional with default value + */ + parameterString?: string; + /** + * This is a simple number that is optional with default value + */ + parameterNumber?: number; + /** + * This is a simple boolean that is optional with default value + */ + parameterBoolean?: boolean; + /** + * This is a simple enum that is optional with default value + */ + parameterEnum?: 'Success' | 'Warning' | 'Error'; + /** + * This is a simple model that is optional with default value + */ + parameterModel?: ModelWithString; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type CallToTestOrderOfParamsData = { + body?: never; + path?: never; + query: { + /** + * This is a optional string with default + */ + parameterOptionalStringWithDefault?: string; + /** + * This is a optional string with empty default + */ + parameterOptionalStringWithEmptyDefault?: string; + /** + * This is a optional string with no default + */ + parameterOptionalStringWithNoDefault?: string; + /** + * This is a string with default + */ + parameterStringWithDefault: string; + /** + * This is a string with empty default + */ + parameterStringWithEmptyDefault: string; + /** + * This is a string with no default + */ + parameterStringWithNoDefault: string; + /** + * This is a string that can be null with no default + */ + parameterStringNullableWithNoDefault?: string | null; + /** + * This is a string that can be null with default + */ + parameterStringNullableWithDefault?: string | null; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type DuplicateNameData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName2Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName3Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName4Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type CallWithNoContentResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no-content'; +}; + +export type CallWithNoContentResponseResponses = { + /** + * Success + */ + 204: void; +}; + +export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; + +export type CallWithResponseAndNoContentResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/response-and-no-content'; +}; + +export type CallWithResponseAndNoContentResponseResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Success + */ + 204: void; +}; + +export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; + +export type DummyAData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/a'; +}; + +export type DummyAResponses = { + 200: _400; +}; + +export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; + +export type DummyBData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/b'; +}; + +export type DummyBResponses = { + /** + * Success + */ + 204: void; +}; + +export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; + +export type CallWithResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithResponseResponses = { + default: Import; +}; + +export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; + +export type CallWithDuplicateResponsesData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithDuplicateResponsesErrors = { + /** + * Message for 500 error + */ + 500: ModelWithStringError; + /** + * Message for 501 error + */ + 501: ModelWithStringError; + /** + * Message for 502 error + */ + 502: ModelWithStringError; + /** + * Message for 4XX errors + */ + '4XX': DictionaryWithArray; + /** + * Default error response + */ + default: ModelWithBoolean; +}; + +export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; + +export type CallWithDuplicateResponsesResponses = { + /** + * Message for 200 response + */ + 200: ModelWithBoolean & ModelWithInteger; + /** + * Message for 201 response + */ + 201: ModelWithString; + /** + * Message for 202 response + */ + 202: ModelWithString; +}; + +export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; + +export type CallWithResponsesData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithResponsesErrors = { + /** + * Message for 500 error + */ + 500: ModelWithStringError; + /** + * Message for 501 error + */ + 501: ModelWithStringError; + /** + * Message for 502 error + */ + 502: ModelWithStringError; + /** + * Message for default response + */ + default: ModelWithStringError; +}; + +export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; + +export type CallWithResponsesResponses = { + /** + * Message for 200 response + */ + 200: { + readonly '@namespace.string'?: string; + readonly '@namespace.integer'?: number; + readonly value?: Array; + }; + /** + * Message for 201 response + */ + 201: ModelThatExtends; + /** + * Message for 202 response + */ + 202: ModelThatExtendsExtends; +}; + +export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; + +export type CollectionFormatData = { + body?: never; + path?: never; + query: { + /** + * This is an array parameter that is sent as csv format (comma-separated values) + */ + parameterArrayCSV: Array | null; + /** + * This is an array parameter that is sent as ssv format (space-separated values) + */ + parameterArraySSV: Array | null; + /** + * This is an array parameter that is sent as tsv format (tab-separated values) + */ + parameterArrayTSV: Array | null; + /** + * This is an array parameter that is sent as pipes format (pipe-separated values) + */ + parameterArrayPipes: Array | null; + /** + * This is an array parameter that is sent as multi format (multiple parameter instances) + */ + parameterArrayMulti: Array | null; + }; + url: '/api/v{api-version}/collectionFormat'; +}; + +export type TypesData = { + body?: never; + path?: { + /** + * This is a number parameter + */ + id?: number; + }; + query: { + /** + * This is a number parameter + */ + parameterNumber: number; + /** + * This is a string parameter + */ + parameterString: string | null; + /** + * This is a boolean parameter + */ + parameterBoolean: boolean | null; + /** + * This is an object parameter + */ + parameterObject: { + [key: string]: unknown; + } | null; + /** + * This is an array parameter + */ + parameterArray: Array | null; + /** + * This is a dictionary parameter + */ + parameterDictionary: { + [key: string]: unknown; + } | null; + /** + * This is an enum parameter + */ + parameterEnum: 'Success' | 'Warning' | 'Error' | null; + }; + url: '/api/v{api-version}/types'; +}; + +export type TypesResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Response is a simple string + */ + 201: string; + /** + * Response is a simple boolean + */ + 202: boolean; + /** + * Response is a simple object + */ + 203: { + [key: string]: unknown; + }; +}; + +export type TypesResponse = TypesResponses[keyof TypesResponses]; + +export type UploadFileData = { + body: Blob | File; + path: { + /** + * api-version should be required in standalone clients + */ + 'api-version': string | null; + }; + query?: never; + url: '/api/v{api-version}/upload'; +}; + +export type UploadFileResponses = { + 200: boolean; +}; + +export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; + +export type FileResponseData = { + body?: never; + path: { + id: string; + /** + * api-version should be required in standalone clients + */ + 'api-version': string; + }; + query?: never; + url: '/api/v{api-version}/file/{id}'; +}; + +export type FileResponseResponses = { + /** + * Success + */ + 200: Blob | File; +}; + +export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; + +export type ComplexTypesData = { + body?: never; + path?: never; + query: { + /** + * Parameter containing object + */ + parameterObject: { + first?: { + second?: { + third?: string; + }; + }; + }; + /** + * Parameter containing reference + */ + parameterReference: ModelWithString; + }; + url: '/api/v{api-version}/complex'; +}; + +export type ComplexTypesErrors = { + /** + * 400 `server` error + */ + 400: unknown; + /** + * 500 server error + */ + 500: unknown; +}; + +export type ComplexTypesResponses = { + /** + * Successful response + */ + 200: Array; +}; + +export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; + +export type MultipartResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multipart'; +}; + +export type MultipartResponseResponses = { + /** + * OK + */ + 200: { + file?: Blob | File; + metadata?: { + foo?: string; + bar?: string; + }; + }; +}; + +export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; + +export type MultipartRequestData = { + body?: { + content?: Blob | File; + data?: ModelWithString | null; + }; + path?: never; + query?: never; + url: '/api/v{api-version}/multipart'; +}; + +export type ComplexParamsData = { + body?: { + readonly key: string | null; + name: string | null; + enabled?: boolean; + type: 'Monkey' | 'Horse' | 'Bird'; + listOfModels?: Array | null; + listOfStrings?: Array | null; + parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; + readonly user?: { + readonly id?: number; + readonly name?: string | null; + }; + }; + path: { + id: number; + /** + * api-version should be required in standalone clients + */ + 'api-version': string; + }; + query?: never; + url: '/api/v{api-version}/complex/{id}'; +}; + +export type ComplexParamsResponses = { + /** + * Success + */ + 200: ModelWithString; +}; + +export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; + +export type CallWithResultFromHeaderData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/header'; +}; + +export type CallWithResultFromHeaderErrors = { + /** + * 400 server error + */ + 400: unknown; + /** + * 500 server error + */ + 500: unknown; +}; + +export type CallWithResultFromHeaderResponses = { + /** + * Successful response + */ + 200: unknown; +}; + +export type TestErrorCodeData = { + body?: never; + path?: never; + query: { + /** + * Status code to return + */ + status: number; + }; + url: '/api/v{api-version}/error'; +}; + +export type TestErrorCodeErrors = { + /** + * Custom message: Internal Server Error + */ + 500: unknown; + /** + * Custom message: Not Implemented + */ + 501: unknown; + /** + * Custom message: Bad Gateway + */ + 502: unknown; + /** + * Custom message: Service Unavailable + */ + 503: unknown; +}; + +export type TestErrorCodeResponses = { + /** + * Custom message: Successful response + */ + 200: unknown; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Data = { + body?: never; + path?: never; + query: { + /** + * Dummy input param + */ + nonAsciiParamæøåÆØÅöôêÊ: number; + }; + url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { + /** + * Successful response + */ + 200: Array; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; + +export type PutWithFormUrlEncodedData = { + body: ArrayWithStrings; + path?: never; + query?: never; + url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/@tanstack/react-query.gen.ts new file mode 100644 index 0000000000..40c8901183 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/@tanstack/react-query.gen.ts @@ -0,0 +1,840 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, skipToken, type UseMutationOptions, useQuery } from '@tanstack/react-query'; + +import { client } from '../client.gen'; +import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; +import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesResponse, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseData, CallWithResponseResponse, CallWithResponsesData, CallWithResponsesError, CallWithResponsesResponse, CallWithResultFromHeaderData, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponse, ComplexTypesData, ComplexTypesResponse, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponse, DummyBData, DummyBResponse, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponse, FooWowData, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationResponse, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, ImportData, ImportResponse, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PatchApiVbyApiVersionNoTagData, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from '../types.gen'; + +export type QueryKey = [ + Pick & { + _id: string; + _infinite?: boolean; + tags?: ReadonlyArray; + } +]; + +const createQueryKey = (id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray): [ + QueryKey[0] +] => { + const params: QueryKey[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey[0]; + if (infinite) { + params._infinite = infinite; + } + if (tags) { + params.tags = tags; + } + if (options?.body) { + params.body = options.body; + } + if (options?.headers) { + params.headers = options.headers; + } + if (options?.path) { + params.path = options.path; + } + if (options?.query) { + params.query = options.query; + } + return [params]; +}; + +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + +export const exportQueryKey = (options?: Options) => createQueryKey('export', options); + +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await export_({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: exportQueryKey(resolveOptions(options)) +}); + +const queryWithOptions = (optionsFn: Function, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +export const useExportQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(exportOptions, options); + +export const patchApiVbyApiVersionNoTagMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await patchApiVbyApiVersionNoTag({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const importMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await import_({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const fooWowMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await fooWow({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); + +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await apiVVersionODataControllerCount({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: apiVVersionODataControllerCountQueryKey(resolveOptions(options)) +}); + +export const useApiVVersionODataControllerCountQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(apiVVersionODataControllerCountOptions, options); + +export const getApiVbyApiVersionSimpleOperationQueryKey = (options: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); + +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await getApiVbyApiVersionSimpleOperation({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: getApiVbyApiVersionSimpleOperationQueryKey(resolveOptions(options)) +}); + +export const useGetApiVbyApiVersionSimpleOperationQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getApiVbyApiVersionSimpleOperationOptions, options); + +export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deleteCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); + +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await getCallWithoutParametersAndResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: getCallWithoutParametersAndResponseQueryKey(resolveOptions(options)) +}); + +export const useGetCallWithoutParametersAndResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithoutParametersAndResponseOptions, options); + +export const patchCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await patchCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const postCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const putCallWithoutParametersAndResponseMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await putCallWithoutParametersAndResponse({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const deleteFooMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deleteFoo({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithDescriptionsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDescriptions({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * @deprecated + */ +export const deprecatedCallMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deprecatedCall({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithParametersMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithParameters({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithWeirdParameterNamesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithWeirdParameterNames({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const getCallWithOptionalParamQueryKey = (options: Options) => createQueryKey('getCallWithOptionalParam', options); + +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await getCallWithOptionalParam({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: getCallWithOptionalParamQueryKey(resolveOptions(options)) +}); + +const createInfiniteParams = [0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { + const params = { ...queryKey[0] }; + if (page.body) { + params.body = { + ...queryKey[0].body as any, + ...page.body as any + }; + } + if (page.headers) { + params.headers = { + ...queryKey[0].headers, + ...page.headers + }; + } + if (page.path) { + params.path = { + ...queryKey[0].path as any, + ...page.path as any + }; + } + if (page.query) { + params.query = { + ...queryKey[0].query as any, + ...page.query as any + }; + } + return params as unknown as typeof page; +}; + +export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); + +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +// @ts-ignore +{ + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { + // @ts-ignore + const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { + query: { + page: pageParam + } + }; + const params = createInfiniteParams(queryKey, page); + const { data } = await getCallWithOptionalParam({ + ...options, + ...params, + signal, + throwOnError: true + }); + return data; + }), + queryKey: getCallWithOptionalParamInfiniteQueryKey(resolveOptions(options)) +}); + +export const useGetCallWithOptionalParamQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(getCallWithOptionalParamOptions, options); + +export const postCallWithOptionalParamMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postCallWithOptionalParam({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const postApiVbyApiVersionRequestBodyMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postApiVbyApiVersionRequestBody({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const postApiVbyApiVersionFormDataMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await postApiVbyApiVersionFormData({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithDefaultParametersQueryKey = (options?: Options) => createQueryKey('callWithDefaultParameters', options); + +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithDefaultParameters({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithDefaultParametersQueryKey(resolveOptions(options)) +}); + +export const useCallWithDefaultParametersQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithDefaultParametersOptions, options); + +export const callWithDefaultOptionalParametersMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDefaultOptionalParameters({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callToTestOrderOfParamsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callToTestOrderOfParams({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateNameMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateName2QueryKey = (options?: Options) => createQueryKey('duplicateName2', options); + +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await duplicateName2({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) +}); + +export const useDuplicateName2Query = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(duplicateName2Options, options); + +export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName3({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const duplicateName4Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await duplicateName4({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithNoContentResponse', options); + +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithNoContentResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithNoContentResponseQueryKey(resolveOptions(options)) +}); + +export const useCallWithNoContentResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithNoContentResponseOptions, options); + +export const callWithResponseAndNoContentResponseQueryKey = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); + +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithResponseAndNoContentResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithResponseAndNoContentResponseQueryKey(resolveOptions(options)) +}); + +export const useCallWithResponseAndNoContentResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseAndNoContentResponseOptions, options); + +export const dummyAQueryKey = (options?: Options) => createQueryKey('dummyA', options); + +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await dummyA({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: dummyAQueryKey(resolveOptions(options)) +}); + +export const useDummyAQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyAOptions, options); + +export const dummyBQueryKey = (options?: Options) => createQueryKey('dummyB', options); + +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await dummyB({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: dummyBQueryKey(resolveOptions(options)) +}); + +export const useDummyBQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(dummyBOptions, options); + +export const callWithResponseQueryKey = (options?: Options) => createQueryKey('callWithResponse', options); + +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await callWithResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) +}); + +export const useCallWithResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(callWithResponseOptions, options); + +export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithDuplicateResponses({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithResponsesMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithResponses({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const collectionFormatQueryKey = (options: Options) => createQueryKey('collectionFormat', options); + +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await collectionFormat({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) +}); + +export const useCollectionFormatQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(collectionFormatOptions, options); + +export const typesQueryKey = (options: Options) => createQueryKey('types', options); + +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await types({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: typesQueryKey(resolveOptions(options)) +}); + +export const useTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(typesOptions, options); + +export const uploadFileMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await uploadFile({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); + +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await fileResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) +}); + +export const useFileResponseQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(fileResponseOptions, options); + +export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); + +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await complexTypes({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) +}); + +export const useComplexTypesQuery = (options: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(complexTypesOptions, options); + +export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); + +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { + const { data } = await multipartResponse({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }), + queryKey: multipartResponseQueryKey(resolveOptions(options)) +}); + +export const useMultipartResponseQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(multipartResponseOptions, options); + +export const multipartRequestMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await multipartRequest({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const complexParamsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await complexParams({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const callWithResultFromHeaderMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await callWithResultFromHeader({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const testErrorCodeMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await testErrorCode({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const nonAsciiæøåÆøÅöôêÊ字符串Mutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await nonAsciiæøåÆøÅöôêÊ字符串({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * Login User + */ +export const putWithFormUrlEncodedMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await putWithFormUrlEncoded({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/client.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/client.gen.ts new file mode 100644 index 0000000000..25cd14eafb --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/client.gen.ts @@ -0,0 +1,16 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type ClientOptions, type Config, createClient, createConfig } from './client'; +import type { ClientOptions as ClientOptions2 } from './types.gen'; + +/** + * The `createClientConfig()` function will be called on client initialization + * and the returned object will become the client's initial configuration. + * + * You may want to initialize your client this way instead of calling + * `setConfig()`. This is useful for example if you're using Next.js + * to ensure your client always has the correct values. + */ +export type CreateClientConfig = (override?: Config) => Config & T>; + +export const client = createClient(createConfig({ baseUrl: 'http://localhost:3000/base' })); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/client/client.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/client/client.gen.ts new file mode 100644 index 0000000000..14dc0a0ec5 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/client/client.gen.ts @@ -0,0 +1,290 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { createSseClient } from '../core/serverSentEvents.gen'; +import type { HttpMethod } from '../core/types.gen'; +import { getValidRequestBody } from '../core/utils.gen'; +import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; +import { + buildUrl, + createConfig, + createInterceptors, + getParseAs, + mergeConfigs, + mergeHeaders, + setAuthParams, +} from './utils.gen'; + +type ReqInit = Omit & { + body?: any; + headers: ReturnType; +}; + +export const createClient = (config: Config = {}): Client => { + let _config = mergeConfigs(createConfig(), config); + + const getConfig = (): Config => ({ ..._config }); + + const setConfig = (config: Config): Config => { + _config = mergeConfigs(_config, config); + return getConfig(); + }; + + const interceptors = createInterceptors(); + + const beforeRequest = async (options: RequestOptions) => { + const opts = { + ..._config, + ...options, + fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, + headers: mergeHeaders(_config.headers, options.headers), + serializedBody: undefined as string | undefined, + }; + + if (opts.security) { + await setAuthParams({ + ...opts, + security: opts.security, + }); + } + + if (opts.requestValidator) { + await opts.requestValidator(opts); + } + + if (opts.body !== undefined && opts.bodySerializer) { + opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; + } + + // remove Content-Type header if body is empty to avoid sending invalid requests + if (opts.body === undefined || opts.serializedBody === '') { + opts.headers.delete('Content-Type'); + } + + const url = buildUrl(opts); + + return { opts, url }; + }; + + const request: Client['request'] = async (options) => { + // @ts-expect-error + const { opts, url } = await beforeRequest(options); + const requestInit: ReqInit = { + redirect: 'follow', + ...opts, + body: getValidRequestBody(opts), + }; + + let request = new Request(url, requestInit); + + for (const fn of interceptors.request.fns) { + if (fn) { + request = await fn(request, opts); + } + } + + // fetch must be assigned here, otherwise it would throw the error: + // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation + const _fetch = opts.fetch!; + let response: Response; + + try { + response = await _fetch(request); + } catch (error) { + // Handle fetch exceptions (AbortError, network errors, etc.) + let finalError = error; + + for (const fn of interceptors.error.fns) { + if (fn) { + finalError = (await fn(error, undefined as any, request, opts)) as unknown; + } + } + + finalError = finalError || ({} as unknown); + + if (opts.throwOnError) { + throw finalError; + } + + // Return error response + return opts.responseStyle === 'data' + ? undefined + : { + error: finalError, + request, + response: undefined as any, + }; + } + + for (const fn of interceptors.response.fns) { + if (fn) { + response = await fn(response, request, opts); + } + } + + const result = { + request, + response, + }; + + if (response.ok) { + const parseAs = + (opts.parseAs === 'auto' + ? getParseAs(response.headers.get('Content-Type')) + : opts.parseAs) ?? 'json'; + + if (response.status === 204 || response.headers.get('Content-Length') === '0') { + let emptyData: any; + switch (parseAs) { + case 'arrayBuffer': + case 'blob': + case 'text': + emptyData = await response[parseAs](); + break; + case 'formData': + emptyData = new FormData(); + break; + case 'stream': + emptyData = response.body; + break; + case 'json': + default: + emptyData = {}; + break; + } + return opts.responseStyle === 'data' + ? emptyData + : { + data: emptyData, + ...result, + }; + } + + let data: any; + switch (parseAs) { + case 'arrayBuffer': + case 'blob': + case 'formData': + case 'text': + data = await response[parseAs](); + break; + case 'json': { + // Some servers return 200 with no Content-Length and empty body. + // response.json() would throw; read as text and parse if non-empty. + const text = await response.text(); + data = text ? JSON.parse(text) : {}; + break; + } + case 'stream': + return opts.responseStyle === 'data' + ? response.body + : { + data: response.body, + ...result, + }; + } + + if (parseAs === 'json') { + if (opts.responseValidator) { + await opts.responseValidator(data); + } + + if (opts.responseTransformer) { + data = await opts.responseTransformer(data); + } + } + + return opts.responseStyle === 'data' + ? data + : { + data, + ...result, + }; + } + + const textError = await response.text(); + let jsonError: unknown; + + try { + jsonError = JSON.parse(textError); + } catch { + // noop + } + + const error = jsonError ?? textError; + let finalError = error; + + for (const fn of interceptors.error.fns) { + if (fn) { + finalError = (await fn(error, response, request, opts)) as string; + } + } + + finalError = finalError || ({} as string); + + if (opts.throwOnError) { + throw finalError; + } + + // TODO: we probably want to return error and improve types + return opts.responseStyle === 'data' + ? undefined + : { + error: finalError, + ...result, + }; + }; + + const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => + request({ ...options, method }); + + const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { + const { opts, url } = await beforeRequest(options); + return createSseClient({ + ...opts, + body: opts.body as BodyInit | null | undefined, + headers: opts.headers as unknown as Record, + method, + onRequest: async (url, init) => { + let request = new Request(url, init); + for (const fn of interceptors.request.fns) { + if (fn) { + request = await fn(request, opts); + } + } + return request; + }, + serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, + url, + }); + }; + + const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); + + return { + buildUrl: _buildUrl, + connect: makeMethodFn('CONNECT'), + delete: makeMethodFn('DELETE'), + get: makeMethodFn('GET'), + getConfig, + head: makeMethodFn('HEAD'), + interceptors, + options: makeMethodFn('OPTIONS'), + patch: makeMethodFn('PATCH'), + post: makeMethodFn('POST'), + put: makeMethodFn('PUT'), + request, + setConfig, + sse: { + connect: makeSseFn('CONNECT'), + delete: makeSseFn('DELETE'), + get: makeSseFn('GET'), + head: makeSseFn('HEAD'), + options: makeSseFn('OPTIONS'), + patch: makeSseFn('PATCH'), + post: makeSseFn('POST'), + put: makeSseFn('PUT'), + trace: makeSseFn('TRACE'), + }, + trace: makeMethodFn('TRACE'), + } as Client; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/client/index.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/client/index.ts new file mode 100644 index 0000000000..b295edeca0 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/client/index.ts @@ -0,0 +1,25 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type { Auth } from '../core/auth.gen'; +export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; +export { + formDataBodySerializer, + jsonBodySerializer, + urlSearchParamsBodySerializer, +} from '../core/bodySerializer.gen'; +export { buildClientParams } from '../core/params.gen'; +export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; +export { createClient } from './client.gen'; +export type { + Client, + ClientOptions, + Config, + CreateClientConfig, + Options, + RequestOptions, + RequestResult, + ResolvedRequestOptions, + ResponseStyle, + TDataShape, +} from './types.gen'; +export { createConfig, mergeHeaders } from './utils.gen'; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/client/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/client/types.gen.ts new file mode 100644 index 0000000000..a3f8616511 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/client/types.gen.ts @@ -0,0 +1,214 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Auth } from '../core/auth.gen'; +import type { + ServerSentEventsOptions, + ServerSentEventsResult, +} from '../core/serverSentEvents.gen'; +import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; +import type { Middleware } from './utils.gen'; + +export type ResponseStyle = 'data' | 'fields'; + +export interface Config + extends Omit, CoreConfig { + /** + * Base URL for all requests made by this client. + */ + baseUrl?: T['baseUrl']; + /** + * Fetch API implementation. You can use this option to provide a custom + * fetch instance. + * + * @default globalThis.fetch + */ + fetch?: typeof fetch; + /** + * Please don't use the Fetch client for Next.js applications. The `next` + * options won't have any effect. + * + * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. + */ + next?: never; + /** + * Return the response data parsed in a specified format. By default, `auto` + * will infer the appropriate method from the `Content-Type` response header. + * You can override this behavior with any of the {@link Body} methods. + * Select `stream` if you don't want to parse response data at all. + * + * @default 'auto' + */ + parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; + /** + * Should we return only data or multiple fields (data, error, response, etc.)? + * + * @default 'fields' + */ + responseStyle?: ResponseStyle; + /** + * Throw an error instead of returning it in the response? + * + * @default false + */ + throwOnError?: T['throwOnError']; +} + +export interface RequestOptions< + TData = unknown, + TResponseStyle extends ResponseStyle = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, +> + extends + Config<{ + responseStyle: TResponseStyle; + throwOnError: ThrowOnError; + }>, + Pick< + ServerSentEventsOptions, + | 'onRequest' + | 'onSseError' + | 'onSseEvent' + | 'sseDefaultRetryDelay' + | 'sseMaxRetryAttempts' + | 'sseMaxRetryDelay' + > { + /** + * Any body that you want to add to your request. + * + * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} + */ + body?: unknown; + path?: Record; + query?: Record; + /** + * Security mechanism(s) to use for the request. + */ + security?: ReadonlyArray; + url: Url; +} + +export interface ResolvedRequestOptions< + TResponseStyle extends ResponseStyle = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, +> extends RequestOptions { + serializedBody?: string; +} + +export type RequestResult< + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = boolean, + TResponseStyle extends ResponseStyle = 'fields', +> = ThrowOnError extends true + ? Promise< + TResponseStyle extends 'data' + ? TData extends Record + ? TData[keyof TData] + : TData + : { + data: TData extends Record ? TData[keyof TData] : TData; + request: Request; + response: Response; + } + > + : Promise< + TResponseStyle extends 'data' + ? (TData extends Record ? TData[keyof TData] : TData) | undefined + : ( + | { + data: TData extends Record ? TData[keyof TData] : TData; + error: undefined; + } + | { + data: undefined; + error: TError extends Record ? TError[keyof TError] : TError; + } + ) & { + request: Request; + response: Response; + } + >; + +export interface ClientOptions { + baseUrl?: string; + responseStyle?: ResponseStyle; + throwOnError?: boolean; +} + +type MethodFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'>, +) => RequestResult; + +type SseFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'>, +) => Promise>; + +type RequestFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'> & + Pick>, 'method'>, +) => RequestResult; + +type BuildUrlFn = < + TData extends { + body?: unknown; + path?: Record; + query?: Record; + url: string; + }, +>( + options: TData & Options, +) => string; + +export type Client = CoreClient & { + interceptors: Middleware; +}; + +/** + * The `createClientConfig()` function will be called on client initialization + * and the returned object will become the client's initial configuration. + * + * You may want to initialize your client this way instead of calling + * `setConfig()`. This is useful for example if you're using Next.js + * to ensure your client always has the correct values. + */ +export type CreateClientConfig = ( + override?: Config, +) => Config & T>; + +export interface TDataShape { + body?: unknown; + headers?: unknown; + path?: unknown; + query?: unknown; + url: string; +} + +type OmitKeys = Pick>; + +export type Options< + TData extends TDataShape = TDataShape, + ThrowOnError extends boolean = boolean, + TResponse = unknown, + TResponseStyle extends ResponseStyle = 'fields', +> = OmitKeys< + RequestOptions, + 'body' | 'path' | 'query' | 'url' +> & + ([TData] extends [never] ? unknown : Omit); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/client/utils.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/client/utils.gen.ts new file mode 100644 index 0000000000..b4bd2435ce --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/client/utils.gen.ts @@ -0,0 +1,316 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { getAuthToken } from '../core/auth.gen'; +import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; +import { jsonBodySerializer } from '../core/bodySerializer.gen'; +import { + serializeArrayParam, + serializeObjectParam, + serializePrimitiveParam, +} from '../core/pathSerializer.gen'; +import { getUrl } from '../core/utils.gen'; +import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; + +export const createQuerySerializer = ({ + parameters = {}, + ...args +}: QuerySerializerOptions = {}) => { + const querySerializer = (queryParams: T) => { + const search: string[] = []; + if (queryParams && typeof queryParams === 'object') { + for (const name in queryParams) { + const value = queryParams[name]; + + if (value === undefined || value === null) { + continue; + } + + const options = parameters[name] || args; + + if (Array.isArray(value)) { + const serializedArray = serializeArrayParam({ + allowReserved: options.allowReserved, + explode: true, + name, + style: 'form', + value, + ...options.array, + }); + if (serializedArray) search.push(serializedArray); + } else if (typeof value === 'object') { + const serializedObject = serializeObjectParam({ + allowReserved: options.allowReserved, + explode: true, + name, + style: 'deepObject', + value: value as Record, + ...options.object, + }); + if (serializedObject) search.push(serializedObject); + } else { + const serializedPrimitive = serializePrimitiveParam({ + allowReserved: options.allowReserved, + name, + value: value as string, + }); + if (serializedPrimitive) search.push(serializedPrimitive); + } + } + } + return search.join('&'); + }; + return querySerializer; +}; + +/** + * Infers parseAs value from provided Content-Type header. + */ +export const getParseAs = (contentType: string | null): Exclude => { + if (!contentType) { + // If no Content-Type header is provided, the best we can do is return the raw response body, + // which is effectively the same as the 'stream' option. + return 'stream'; + } + + const cleanContent = contentType.split(';')[0]?.trim(); + + if (!cleanContent) { + return; + } + + if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { + return 'json'; + } + + if (cleanContent === 'multipart/form-data') { + return 'formData'; + } + + if ( + ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) + ) { + return 'blob'; + } + + if (cleanContent.startsWith('text/')) { + return 'text'; + } + + return; +}; + +const checkForExistence = ( + options: Pick & { + headers: Headers; + }, + name?: string, +): boolean => { + if (!name) { + return false; + } + if ( + options.headers.has(name) || + options.query?.[name] || + options.headers.get('Cookie')?.includes(`${name}=`) + ) { + return true; + } + return false; +}; + +export const setAuthParams = async ({ + security, + ...options +}: Pick, 'security'> & + Pick & { + headers: Headers; + }) => { + for (const auth of security) { + if (checkForExistence(options, auth.name)) { + continue; + } + + const token = await getAuthToken(auth, options.auth); + + if (!token) { + continue; + } + + const name = auth.name ?? 'Authorization'; + + switch (auth.in) { + case 'query': + if (!options.query) { + options.query = {}; + } + options.query[name] = token; + break; + case 'cookie': + options.headers.append('Cookie', `${name}=${token}`); + break; + case 'header': + default: + options.headers.set(name, token); + break; + } + } +}; + +export const buildUrl: Client['buildUrl'] = (options) => + getUrl({ + baseUrl: options.baseUrl as string, + path: options.path, + query: options.query, + querySerializer: + typeof options.querySerializer === 'function' + ? options.querySerializer + : createQuerySerializer(options.querySerializer), + url: options.url, + }); + +export const mergeConfigs = (a: Config, b: Config): Config => { + const config = { ...a, ...b }; + if (config.baseUrl?.endsWith('/')) { + config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); + } + config.headers = mergeHeaders(a.headers, b.headers); + return config; +}; + +const headersEntries = (headers: Headers): Array<[string, string]> => { + const entries: Array<[string, string]> = []; + headers.forEach((value, key) => { + entries.push([key, value]); + }); + return entries; +}; + +export const mergeHeaders = ( + ...headers: Array['headers'] | undefined> +): Headers => { + const mergedHeaders = new Headers(); + for (const header of headers) { + if (!header) { + continue; + } + + const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); + + for (const [key, value] of iterator) { + if (value === null) { + mergedHeaders.delete(key); + } else if (Array.isArray(value)) { + for (const v of value) { + mergedHeaders.append(key, v as string); + } + } else if (value !== undefined) { + // assume object headers are meant to be JSON stringified, i.e. their + // content value in OpenAPI specification is 'application/json' + mergedHeaders.set( + key, + typeof value === 'object' ? JSON.stringify(value) : (value as string), + ); + } + } + } + return mergedHeaders; +}; + +type ErrInterceptor = ( + error: Err, + response: Res, + request: Req, + options: Options, +) => Err | Promise; + +type ReqInterceptor = (request: Req, options: Options) => Req | Promise; + +type ResInterceptor = ( + response: Res, + request: Req, + options: Options, +) => Res | Promise; + +class Interceptors { + fns: Array = []; + + clear(): void { + this.fns = []; + } + + eject(id: number | Interceptor): void { + const index = this.getInterceptorIndex(id); + if (this.fns[index]) { + this.fns[index] = null; + } + } + + exists(id: number | Interceptor): boolean { + const index = this.getInterceptorIndex(id); + return Boolean(this.fns[index]); + } + + getInterceptorIndex(id: number | Interceptor): number { + if (typeof id === 'number') { + return this.fns[id] ? id : -1; + } + return this.fns.indexOf(id); + } + + update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { + const index = this.getInterceptorIndex(id); + if (this.fns[index]) { + this.fns[index] = fn; + return id; + } + return false; + } + + use(fn: Interceptor): number { + this.fns.push(fn); + return this.fns.length - 1; + } +} + +export interface Middleware { + error: Interceptors>; + request: Interceptors>; + response: Interceptors>; +} + +export const createInterceptors = (): Middleware< + Req, + Res, + Err, + Options +> => ({ + error: new Interceptors>(), + request: new Interceptors>(), + response: new Interceptors>(), +}); + +const defaultQuerySerializer = createQuerySerializer({ + allowReserved: false, + array: { + explode: true, + style: 'form', + }, + object: { + explode: true, + style: 'deepObject', + }, +}); + +const defaultHeaders = { + 'Content-Type': 'application/json', +}; + +export const createConfig = ( + override: Config & T> = {}, +): Config & T> => ({ + ...jsonBodySerializer, + headers: defaultHeaders, + parseAs: 'auto', + querySerializer: defaultQuerySerializer, + ...override, +}); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/auth.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/auth.gen.ts new file mode 100644 index 0000000000..3ebf994788 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/auth.gen.ts @@ -0,0 +1,41 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type AuthToken = string | undefined; + +export interface Auth { + /** + * Which part of the request do we use to send the auth? + * + * @default 'header' + */ + in?: 'header' | 'query' | 'cookie'; + /** + * Header or query parameter name. + * + * @default 'Authorization' + */ + name?: string; + scheme?: 'basic' | 'bearer'; + type: 'apiKey' | 'http'; +} + +export const getAuthToken = async ( + auth: Auth, + callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, +): Promise => { + const token = typeof callback === 'function' ? await callback(auth) : callback; + + if (!token) { + return; + } + + if (auth.scheme === 'bearer') { + return `Bearer ${token}`; + } + + if (auth.scheme === 'basic') { + return `Basic ${btoa(token)}`; + } + + return token; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/bodySerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/bodySerializer.gen.ts new file mode 100644 index 0000000000..67daca60f8 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/bodySerializer.gen.ts @@ -0,0 +1,82 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; + +export type QuerySerializer = (query: Record) => string; + +export type BodySerializer = (body: unknown) => unknown; + +type QuerySerializerOptionsObject = { + allowReserved?: boolean; + array?: Partial>; + object?: Partial>; +}; + +export type QuerySerializerOptions = QuerySerializerOptionsObject & { + /** + * Per-parameter serialization overrides. When provided, these settings + * override the global array/object settings for specific parameter names. + */ + parameters?: Record; +}; + +const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { + if (typeof value === 'string' || value instanceof Blob) { + data.append(key, value); + } else if (value instanceof Date) { + data.append(key, value.toISOString()); + } else { + data.append(key, JSON.stringify(value)); + } +}; + +const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { + if (typeof value === 'string') { + data.append(key, value); + } else { + data.append(key, JSON.stringify(value)); + } +}; + +export const formDataBodySerializer = { + bodySerializer: (body: unknown): FormData => { + const data = new FormData(); + + Object.entries(body as Record).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + if (Array.isArray(value)) { + value.forEach((v) => serializeFormDataPair(data, key, v)); + } else { + serializeFormDataPair(data, key, value); + } + }); + + return data; + }, +}; + +export const jsonBodySerializer = { + bodySerializer: (body: unknown): string => + JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), +}; + +export const urlSearchParamsBodySerializer = { + bodySerializer: (body: unknown): string => { + const data = new URLSearchParams(); + + Object.entries(body as Record).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + if (Array.isArray(value)) { + value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); + } else { + serializeUrlSearchParamsPair(data, key, value); + } + }); + + return data.toString(); + }, +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/params.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/params.gen.ts new file mode 100644 index 0000000000..7955601a5c --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/params.gen.ts @@ -0,0 +1,169 @@ +// This file is auto-generated by @hey-api/openapi-ts + +type Slot = 'body' | 'headers' | 'path' | 'query'; + +export type Field = + | { + in: Exclude; + /** + * Field name. This is the name we want the user to see and use. + */ + key: string; + /** + * Field mapped name. This is the name we want to use in the request. + * If omitted, we use the same value as `key`. + */ + map?: string; + } + | { + in: Extract; + /** + * Key isn't required for bodies. + */ + key?: string; + map?: string; + } + | { + /** + * Field name. This is the name we want the user to see and use. + */ + key: string; + /** + * Field mapped name. This is the name we want to use in the request. + * If `in` is omitted, `map` aliases `key` to the transport layer. + */ + map: Slot; + }; + +export interface Fields { + allowExtra?: Partial>; + args?: ReadonlyArray; +} + +export type FieldsConfig = ReadonlyArray; + +const extraPrefixesMap: Record = { + $body_: 'body', + $headers_: 'headers', + $path_: 'path', + $query_: 'query', +}; +const extraPrefixes = Object.entries(extraPrefixesMap); + +type KeyMap = Map< + string, + | { + in: Slot; + map?: string; + } + | { + in?: never; + map: Slot; + } +>; + +const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { + if (!map) { + map = new Map(); + } + + for (const config of fields) { + if ('in' in config) { + if (config.key) { + map.set(config.key, { + in: config.in, + map: config.map, + }); + } + } else if ('key' in config) { + map.set(config.key, { + map: config.map, + }); + } else if (config.args) { + buildKeyMap(config.args, map); + } + } + + return map; +}; + +interface Params { + body: unknown; + headers: Record; + path: Record; + query: Record; +} + +const stripEmptySlots = (params: Params) => { + for (const [slot, value] of Object.entries(params)) { + if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { + delete params[slot as Slot]; + } + } +}; + +export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { + const params: Params = { + body: {}, + headers: {}, + path: {}, + query: {}, + }; + + const map = buildKeyMap(fields); + + let config: FieldsConfig[number] | undefined; + + for (const [index, arg] of args.entries()) { + if (fields[index]) { + config = fields[index]; + } + + if (!config) { + continue; + } + + if ('in' in config) { + if (config.key) { + const field = map.get(config.key)!; + const name = field.map || config.key; + if (field.in) { + (params[field.in] as Record)[name] = arg; + } + } else { + params.body = arg; + } + } else { + for (const [key, value] of Object.entries(arg ?? {})) { + const field = map.get(key); + + if (field) { + if (field.in) { + const name = field.map || key; + (params[field.in] as Record)[name] = value; + } else { + params[field.map] = value; + } + } else { + const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); + + if (extra) { + const [prefix, slot] = extra; + (params[slot] as Record)[key.slice(prefix.length)] = value; + } else if ('allowExtra' in config && config.allowExtra) { + for (const [slot, allowed] of Object.entries(config.allowExtra)) { + if (allowed) { + (params[slot as Slot] as Record)[key] = value; + break; + } + } + } + } + } + } + } + + stripEmptySlots(params); + + return params; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/pathSerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/pathSerializer.gen.ts new file mode 100644 index 0000000000..994b2848c6 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/pathSerializer.gen.ts @@ -0,0 +1,171 @@ +// This file is auto-generated by @hey-api/openapi-ts + +interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} + +interface SerializePrimitiveOptions { + allowReserved?: boolean; + name: string; +} + +export interface SerializerOptions { + /** + * @default true + */ + explode: boolean; + style: T; +} + +export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; +export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; +type MatrixStyle = 'label' | 'matrix' | 'simple'; +export type ObjectStyle = 'form' | 'deepObject'; +type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; + +interface SerializePrimitiveParam extends SerializePrimitiveOptions { + value: string; +} + +export const separatorArrayExplode = (style: ArraySeparatorStyle) => { + switch (style) { + case 'label': + return '.'; + case 'matrix': + return ';'; + case 'simple': + return ','; + default: + return '&'; + } +}; + +export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { + switch (style) { + case 'form': + return ','; + case 'pipeDelimited': + return '|'; + case 'spaceDelimited': + return '%20'; + default: + return ','; + } +}; + +export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { + switch (style) { + case 'label': + return '.'; + case 'matrix': + return ';'; + case 'simple': + return ','; + default: + return '&'; + } +}; + +export const serializeArrayParam = ({ + allowReserved, + explode, + name, + style, + value, +}: SerializeOptions & { + value: unknown[]; +}) => { + if (!explode) { + const joinedValues = ( + allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) + ).join(separatorArrayNoExplode(style)); + switch (style) { + case 'label': + return `.${joinedValues}`; + case 'matrix': + return `;${name}=${joinedValues}`; + case 'simple': + return joinedValues; + default: + return `${name}=${joinedValues}`; + } + } + + const separator = separatorArrayExplode(style); + const joinedValues = value + .map((v) => { + if (style === 'label' || style === 'simple') { + return allowReserved ? v : encodeURIComponent(v as string); + } + + return serializePrimitiveParam({ + allowReserved, + name, + value: v as string, + }); + }) + .join(separator); + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; +}; + +export const serializePrimitiveParam = ({ + allowReserved, + name, + value, +}: SerializePrimitiveParam) => { + if (value === undefined || value === null) { + return ''; + } + + if (typeof value === 'object') { + throw new Error( + 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', + ); + } + + return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; +}; + +export const serializeObjectParam = ({ + allowReserved, + explode, + name, + style, + value, + valueOnly, +}: SerializeOptions & { + value: Record | Date; + valueOnly?: boolean; +}) => { + if (value instanceof Date) { + return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; + } + + if (style !== 'deepObject' && !explode) { + let values: string[] = []; + Object.entries(value).forEach(([key, v]) => { + values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; + }); + const joinedValues = values.join(','); + switch (style) { + case 'form': + return `${name}=${joinedValues}`; + case 'label': + return `.${joinedValues}`; + case 'matrix': + return `;${name}=${joinedValues}`; + default: + return joinedValues; + } + } + + const separator = separatorObjectExplode(style); + const joinedValues = Object.entries(value) + .map(([key, v]) => + serializePrimitiveParam({ + allowReserved, + name: style === 'deepObject' ? `${name}[${key}]` : key, + value: v as string, + }), + ) + .join(separator); + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/queryKeySerializer.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/queryKeySerializer.gen.ts new file mode 100644 index 0000000000..5000df606f --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/queryKeySerializer.gen.ts @@ -0,0 +1,117 @@ +// This file is auto-generated by @hey-api/openapi-ts + +/** + * JSON-friendly union that mirrors what Pinia Colada can hash. + */ +export type JsonValue = + | null + | string + | number + | boolean + | JsonValue[] + | { [key: string]: JsonValue }; + +/** + * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. + */ +export const queryKeyJsonReplacer = (_key: string, value: unknown) => { + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { + return undefined; + } + if (typeof value === 'bigint') { + return value.toString(); + } + if (value instanceof Date) { + return value.toISOString(); + } + return value; +}; + +/** + * Safely stringifies a value and parses it back into a JsonValue. + */ +export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { + try { + const json = JSON.stringify(input, queryKeyJsonReplacer); + if (json === undefined) { + return undefined; + } + return JSON.parse(json) as JsonValue; + } catch { + return undefined; + } +}; + +/** + * Detects plain objects (including objects with a null prototype). + */ +const isPlainObject = (value: unknown): value is Record => { + if (value === null || typeof value !== 'object') { + return false; + } + const prototype = Object.getPrototypeOf(value as object); + return prototype === Object.prototype || prototype === null; +}; + +/** + * Turns URLSearchParams into a sorted JSON object for deterministic keys. + */ +const serializeSearchParams = (params: URLSearchParams): JsonValue => { + const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); + const result: Record = {}; + + for (const [key, value] of entries) { + const existing = result[key]; + if (existing === undefined) { + result[key] = value; + continue; + } + + if (Array.isArray(existing)) { + (existing as string[]).push(value); + } else { + result[key] = [existing, value]; + } + } + + return result; +}; + +/** + * Normalizes any accepted value into a JSON-friendly shape for query keys. + */ +export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { + if (value === null) { + return null; + } + + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return value; + } + + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { + return undefined; + } + + if (typeof value === 'bigint') { + return value.toString(); + } + + if (value instanceof Date) { + return value.toISOString(); + } + + if (Array.isArray(value)) { + return stringifyToJsonValue(value); + } + + if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { + return serializeSearchParams(value); + } + + if (isPlainObject(value)) { + return stringifyToJsonValue(value); + } + + return undefined; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/serverSentEvents.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/serverSentEvents.gen.ts new file mode 100644 index 0000000000..6aa6cf02a4 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/serverSentEvents.gen.ts @@ -0,0 +1,243 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Config } from './types.gen'; + +export type ServerSentEventsOptions = Omit & + Pick & { + /** + * Fetch API implementation. You can use this option to provide a custom + * fetch instance. + * + * @default globalThis.fetch + */ + fetch?: typeof fetch; + /** + * Implementing clients can call request interceptors inside this hook. + */ + onRequest?: (url: string, init: RequestInit) => Promise; + /** + * Callback invoked when a network or parsing error occurs during streaming. + * + * This option applies only if the endpoint returns a stream of events. + * + * @param error The error that occurred. + */ + onSseError?: (error: unknown) => void; + /** + * Callback invoked when an event is streamed from the server. + * + * This option applies only if the endpoint returns a stream of events. + * + * @param event Event streamed from the server. + * @returns Nothing (void). + */ + onSseEvent?: (event: StreamEvent) => void; + serializedBody?: RequestInit['body']; + /** + * Default retry delay in milliseconds. + * + * This option applies only if the endpoint returns a stream of events. + * + * @default 3000 + */ + sseDefaultRetryDelay?: number; + /** + * Maximum number of retry attempts before giving up. + */ + sseMaxRetryAttempts?: number; + /** + * Maximum retry delay in milliseconds. + * + * Applies only when exponential backoff is used. + * + * This option applies only if the endpoint returns a stream of events. + * + * @default 30000 + */ + sseMaxRetryDelay?: number; + /** + * Optional sleep function for retry backoff. + * + * Defaults to using `setTimeout`. + */ + sseSleepFn?: (ms: number) => Promise; + url: string; + }; + +export interface StreamEvent { + data: TData; + event?: string; + id?: string; + retry?: number; +} + +export type ServerSentEventsResult = { + stream: AsyncGenerator< + TData extends Record ? TData[keyof TData] : TData, + TReturn, + TNext + >; +}; + +export const createSseClient = ({ + onRequest, + onSseError, + onSseEvent, + responseTransformer, + responseValidator, + sseDefaultRetryDelay, + sseMaxRetryAttempts, + sseMaxRetryDelay, + sseSleepFn, + url, + ...options +}: ServerSentEventsOptions): ServerSentEventsResult => { + let lastEventId: string | undefined; + + const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + + const createStream = async function* () { + let retryDelay: number = sseDefaultRetryDelay ?? 3000; + let attempt = 0; + const signal = options.signal ?? new AbortController().signal; + + while (true) { + if (signal.aborted) break; + + attempt++; + + const headers = + options.headers instanceof Headers + ? options.headers + : new Headers(options.headers as Record | undefined); + + if (lastEventId !== undefined) { + headers.set('Last-Event-ID', lastEventId); + } + + try { + const requestInit: RequestInit = { + redirect: 'follow', + ...options, + body: options.serializedBody, + headers, + signal, + }; + let request = new Request(url, requestInit); + if (onRequest) { + request = await onRequest(url, requestInit); + } + // fetch must be assigned here, otherwise it would throw the error: + // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation + const _fetch = options.fetch ?? globalThis.fetch; + const response = await _fetch(request); + + if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); + + if (!response.body) throw new Error('No body in SSE response'); + + const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); + + let buffer = ''; + + const abortHandler = () => { + try { + reader.cancel(); + } catch { + // noop + } + }; + + signal.addEventListener('abort', abortHandler); + + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + buffer += value; + // Normalize line endings: CRLF -> LF, then CR -> LF + buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); + + const chunks = buffer.split('\n\n'); + buffer = chunks.pop() ?? ''; + + for (const chunk of chunks) { + const lines = chunk.split('\n'); + const dataLines: Array = []; + let eventName: string | undefined; + + for (const line of lines) { + if (line.startsWith('data:')) { + dataLines.push(line.replace(/^data:\s*/, '')); + } else if (line.startsWith('event:')) { + eventName = line.replace(/^event:\s*/, ''); + } else if (line.startsWith('id:')) { + lastEventId = line.replace(/^id:\s*/, ''); + } else if (line.startsWith('retry:')) { + const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); + if (!Number.isNaN(parsed)) { + retryDelay = parsed; + } + } + } + + let data: unknown; + let parsedJson = false; + + if (dataLines.length) { + const rawData = dataLines.join('\n'); + try { + data = JSON.parse(rawData); + parsedJson = true; + } catch { + data = rawData; + } + } + + if (parsedJson) { + if (responseValidator) { + await responseValidator(data); + } + + if (responseTransformer) { + data = await responseTransformer(data); + } + } + + onSseEvent?.({ + data, + event: eventName, + id: lastEventId, + retry: retryDelay, + }); + + if (dataLines.length) { + yield data as any; + } + } + } + } finally { + signal.removeEventListener('abort', abortHandler); + reader.releaseLock(); + } + + break; // exit loop on normal completion + } catch (error) { + // connection failed or aborted; retry after delay + onSseError?.(error); + + if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { + break; // stop after firing error + } + + // exponential backoff: double retry each attempt, cap at 30s + const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); + await sleep(backoff); + } + } + }; + + const stream = createStream(); + + return { stream }; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/types.gen.ts new file mode 100644 index 0000000000..97463257e4 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/types.gen.ts @@ -0,0 +1,104 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Auth, AuthToken } from './auth.gen'; +import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; + +export type HttpMethod = + | 'connect' + | 'delete' + | 'get' + | 'head' + | 'options' + | 'patch' + | 'post' + | 'put' + | 'trace'; + +export type Client< + RequestFn = never, + Config = unknown, + MethodFn = never, + BuildUrlFn = never, + SseFn = never, +> = { + /** + * Returns the final request URL. + */ + buildUrl: BuildUrlFn; + getConfig: () => Config; + request: RequestFn; + setConfig: (config: Config) => Config; +} & { + [K in HttpMethod]: MethodFn; +} & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); + +export interface Config { + /** + * Auth token or a function returning auth token. The resolved value will be + * added to the request payload as defined by its `security` array. + */ + auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; + /** + * A function for serializing request body parameter. By default, + * {@link JSON.stringify()} will be used. + */ + bodySerializer?: BodySerializer | null; + /** + * An object containing any HTTP headers that you want to pre-populate your + * `Headers` object with. + * + * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} + */ + headers?: + | RequestInit['headers'] + | Record< + string, + string | number | boolean | (string | number | boolean)[] | null | undefined | unknown + >; + /** + * The request method. + * + * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} + */ + method?: Uppercase; + /** + * A function for serializing request query parameters. By default, arrays + * will be exploded in form style, objects will be exploded in deepObject + * style, and reserved characters are percent-encoded. + * + * This method will have no effect if the native `paramsSerializer()` Axios + * API function is used. + * + * {@link https://swagger.io/docs/specification/serialization/#query View examples} + */ + querySerializer?: QuerySerializer | QuerySerializerOptions; + /** + * A function validating request data. This is useful if you want to ensure + * the request conforms to the desired shape, so it can be safely sent to + * the server. + */ + requestValidator?: (data: unknown) => Promise; + /** + * A function transforming response data before it's returned. This is useful + * for post-processing data, e.g. converting ISO strings into Date objects. + */ + responseTransformer?: (data: unknown) => Promise; + /** + * A function validating response data. This is useful if you want to ensure + * the response conforms to the desired shape, so it can be safely passed to + * the transformers and returned to the user. + */ + responseValidator?: (data: unknown) => Promise; +} + +type IsExactlyNeverOrNeverUndefined = [T] extends [never] + ? true + : [T] extends [never | undefined] + ? [undefined] extends [T] + ? false + : true + : false; + +export type OmitNever> = { + [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/utils.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/utils.gen.ts new file mode 100644 index 0000000000..e7ddbe3541 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/core/utils.gen.ts @@ -0,0 +1,140 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; +import { + type ArraySeparatorStyle, + serializeArrayParam, + serializeObjectParam, + serializePrimitiveParam, +} from './pathSerializer.gen'; + +export interface PathSerializer { + path: Record; + url: string; +} + +export const PATH_PARAM_RE = /\{[^{}]+\}/g; + +export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { + let url = _url; + const matches = _url.match(PATH_PARAM_RE); + if (matches) { + for (const match of matches) { + let explode = false; + let name = match.substring(1, match.length - 1); + let style: ArraySeparatorStyle = 'simple'; + + if (name.endsWith('*')) { + explode = true; + name = name.substring(0, name.length - 1); + } + + if (name.startsWith('.')) { + name = name.substring(1); + style = 'label'; + } else if (name.startsWith(';')) { + name = name.substring(1); + style = 'matrix'; + } + + const value = path[name]; + + if (value === undefined || value === null) { + continue; + } + + if (Array.isArray(value)) { + url = url.replace(match, serializeArrayParam({ explode, name, style, value })); + continue; + } + + if (typeof value === 'object') { + url = url.replace( + match, + serializeObjectParam({ + explode, + name, + style, + value: value as Record, + valueOnly: true, + }), + ); + continue; + } + + if (style === 'matrix') { + url = url.replace( + match, + `;${serializePrimitiveParam({ + name, + value: value as string, + })}`, + ); + continue; + } + + const replaceValue = encodeURIComponent( + style === 'label' ? `.${value as string}` : (value as string), + ); + url = url.replace(match, replaceValue); + } + } + return url; +}; + +export const getUrl = ({ + baseUrl, + path, + query, + querySerializer, + url: _url, +}: { + baseUrl?: string; + path?: Record; + query?: Record; + querySerializer: QuerySerializer; + url: string; +}) => { + const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; + let url = (baseUrl ?? '') + pathUrl; + if (path) { + url = defaultPathSerializer({ path, url }); + } + let search = query ? querySerializer(query) : ''; + if (search.startsWith('?')) { + search = search.substring(1); + } + if (search) { + url += `?${search}`; + } + return url; +}; + +export function getValidRequestBody(options: { + body?: unknown; + bodySerializer?: BodySerializer | null; + serializedBody?: unknown; +}) { + const hasBody = options.body !== undefined; + const isSerializedBody = hasBody && options.bodySerializer; + + if (isSerializedBody) { + if ('serializedBody' in options) { + const hasSerializedBody = + options.serializedBody !== undefined && options.serializedBody !== ''; + + return hasSerializedBody ? options.serializedBody : null; + } + + // not all clients implement a serializedBody property (i.e. client-axios) + return options.body !== '' ? options.body : null; + } + + // plain/text body + if (hasBody) { + return options.body; + } + + // no body was provided + return undefined; +} diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/index.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/index.ts new file mode 100644 index 0000000000..6e132194fd --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/index.ts @@ -0,0 +1,4 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, headCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, optionsCallWithoutParametersAndResponse, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from './sdk.gen'; +export type { _3eNum1Период, _400, AdditionalPropertiesIntegerIssue, AdditionalPropertiesUnknownIssue, AdditionalPropertiesUnknownIssue2, AdditionalPropertiesUnknownIssue3, AdditionalPropertiesUnknownIssueWritable, AnyOfAnyAndNull, AnyOfArrays, ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponse, ApiVVersionODataControllerCountResponses, ArrayWithAnyOfProperties, ArrayWithArray, ArrayWithBooleans, ArrayWithNumbers, ArrayWithProperties, ArrayWithReferences, ArrayWithStrings, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesError, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponse, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponse, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponse, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponse, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesError, CallWithResponsesErrors, CallWithResponsesResponse, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CamelCaseCommentWithBreaks, CharactersInDescription, ClientOptions, CollectionFormatData, CommentWithBackticks, CommentWithBackticksAndQuotes, CommentWithBreaks, CommentWithExpressionPlaceholders, CommentWithQuotes, CommentWithReservedCharacters, CommentWithSlashes, ComplexParamsData, ComplexParamsResponse, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponse, ComplexTypesResponses, CompositionBaseModel, CompositionExtendedModel, CompositionWithAllOfAndNullable, CompositionWithAnyOf, CompositionWithAnyOfAndNullable, CompositionWithAnyOfAnonymous, CompositionWithNestedAnyAndTypeNull, CompositionWithNestedAnyOfAndNull, CompositionWithOneOf, CompositionWithOneOfAndComplexArrayDictionary, CompositionWithOneOfAndNullable, CompositionWithOneOfAndProperties, CompositionWithOneOfAndSimpleArrayDictionary, CompositionWithOneOfAndSimpleDictionary, CompositionWithOneOfAnonymous, CompositionWithOneOfDiscriminator, ConstValue, Default, DeleteCallWithoutParametersAndResponseData, DeleteFooData, DeleteFooData2, DeleteFooData3, DeprecatedCallData, DeprecatedModel, DictionaryWithArray, DictionaryWithDictionary, DictionaryWithProperties, DictionaryWithPropertiesAndAdditionalProperties, DictionaryWithReference, DictionaryWithString, DummyAData, DummyAResponse, DummyAResponses, DummyBData, DummyBResponse, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, EnumFromDescription, EnumWithExtensions, EnumWithNumbers, EnumWithReplacedCharacters, EnumWithStrings, EnumWithXEnumNames, ExportData, ExternalRefA, ExternalRefB, ExternalSharedModel, File, FileResponseData, FileResponseResponse, FileResponseResponses, FileWritable, FooWowData, FooWowResponses, FreeFormObjectWithAdditionalPropertiesEqEmptyObject, FreeFormObjectWithAdditionalPropertiesEqTrue, FreeFormObjectWithoutAdditionalProperties, GenericSchemaDuplicateIssue1SystemBoolean, GenericSchemaDuplicateIssue1SystemBooleanWritable, GenericSchemaDuplicateIssue1SystemString, GenericSchemaDuplicateIssue1SystemStringWritable, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationError, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponse, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, Import, ImportData, ImportResponse, ImportResponses, IoK8sApimachineryPkgApisMetaV1DeleteOptions, IoK8sApimachineryPkgApisMetaV1Preconditions, ModelCircle, ModelFromZendesk, ModelSquare, ModelThatExtends, ModelThatExtendsExtends, ModelWithAdditionalPropertiesEqTrue, ModelWithAdditionalPropertiesRef, ModelWithAnyOfConstantSizeArray, ModelWithAnyOfConstantSizeArrayAndIntersect, ModelWithAnyOfConstantSizeArrayNullable, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions, ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable, ModelWithArray, ModelWithArrayReadOnlyAndWriteOnly, ModelWithArrayReadOnlyAndWriteOnlyWritable, ModelWithBackticksInDescription, ModelWithBoolean, ModelWithCircularReference, ModelWithConst, ModelWithConstantSizeArray, ModelWithDictionary, ModelWithDuplicateImports, ModelWithDuplicateProperties, ModelWithEnum, ModelWithEnumFromDescription, ModelWithEnumWithHyphen, ModelWithInteger, ModelWithNestedArrayEnums, ModelWithNestedArrayEnumsData, ModelWithNestedArrayEnumsDataBar, ModelWithNestedArrayEnumsDataFoo, ModelWithNestedCompositionEnums, ModelWithNestedEnums, ModelWithNestedProperties, ModelWithNullableObject, ModelWithNullableString, ModelWithNumericEnumUnion, ModelWithOneOfAndProperties, ModelWithOneOfEnum, ModelWithOrderedProperties, ModelWithPattern, ModelWithPatternWritable, ModelWithPrefixItemsConstantSizeArray, ModelWithProperties, ModelWithPropertiesWritable, ModelWithReadOnlyAndWriteOnly, ModelWithReadOnlyAndWriteOnlyWritable, ModelWithReference, ModelWithReferenceWritable, ModelWithString, ModelWithStringError, MultipartRequestData, MultipartResponseData, MultipartResponseResponse, MultipartResponseResponses, NestedAnyOfArraysNullable, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, NonAsciiæøåÆøÅöôêÊ字符串Responses, NonAsciiStringæøåÆøÅöôêÊ字符串, NullableObject, OneOfAllOfIssue, OneOfAllOfIssueWritable, OptionsCallWithoutParametersAndResponseData, Pageable, ParameterSimpleParameterUnused, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PostServiceWithEmptyTagResponse, PostServiceWithEmptyTagResponse2, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, SchemaWithFormRestrictedKeys, SimpleBoolean, SimpleFile, SimpleFormData, SimpleInteger, SimpleParameter, SimpleReference, SimpleRequestBody, SimpleString, SimpleStringWithPattern, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponse, TypesResponses, UploadFileData, UploadFileResponse, UploadFileResponses, XFooBar } from './types.gen'; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/sdk.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/sdk.gen.ts new file mode 100644 index 0000000000..e48dcff8cf --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/sdk.gen.ts @@ -0,0 +1,206 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; +import { client } from './client.gen'; +import type { ApiVVersionODataControllerCountData, ApiVVersionODataControllerCountResponses, CallToTestOrderOfParamsData, CallWithDefaultOptionalParametersData, CallWithDefaultParametersData, CallWithDescriptionsData, CallWithDuplicateResponsesData, CallWithDuplicateResponsesErrors, CallWithDuplicateResponsesResponses, CallWithNoContentResponseData, CallWithNoContentResponseResponses, CallWithParametersData, CallWithResponseAndNoContentResponseData, CallWithResponseAndNoContentResponseResponses, CallWithResponseData, CallWithResponseResponses, CallWithResponsesData, CallWithResponsesErrors, CallWithResponsesResponses, CallWithResultFromHeaderData, CallWithResultFromHeaderErrors, CallWithResultFromHeaderResponses, CallWithWeirdParameterNamesData, CollectionFormatData, ComplexParamsData, ComplexParamsResponses, ComplexTypesData, ComplexTypesErrors, ComplexTypesResponses, DeleteCallWithoutParametersAndResponseData, DeleteFooData3, DeprecatedCallData, DummyAData, DummyAResponses, DummyBData, DummyBResponses, DuplicateName2Data, DuplicateName3Data, DuplicateName4Data, DuplicateNameData, ExportData, FileResponseData, FileResponseResponses, FooWowData, FooWowResponses, GetApiVbyApiVersionSimpleOperationData, GetApiVbyApiVersionSimpleOperationErrors, GetApiVbyApiVersionSimpleOperationResponses, GetCallWithOptionalParamData, GetCallWithoutParametersAndResponseData, HeadCallWithoutParametersAndResponseData, ImportData, ImportResponses, MultipartRequestData, MultipartResponseData, MultipartResponseResponses, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Responses, OptionsCallWithoutParametersAndResponseData, PatchApiVbyApiVersionNoTagData, PatchApiVbyApiVersionNoTagResponses, PatchCallWithoutParametersAndResponseData, PostApiVbyApiVersionFormDataData, PostApiVbyApiVersionRequestBodyData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponses, PostCallWithoutParametersAndResponseData, PutCallWithoutParametersAndResponseData, PutWithFormUrlEncodedData, TestErrorCodeData, TestErrorCodeErrors, TestErrorCodeResponses, TypesData, TypesResponses, UploadFileData, UploadFileResponses } from './types.gen'; + +export type Options = Options2 & { + /** + * You can provide a client instance returned by `createClient()` instead of + * individual options. This might be also useful if you want to implement a + * custom client. + */ + client?: Client; + /** + * You can pass arbitrary values through the `meta` object. This can be + * used to access values that aren't defined as part of the SDK function. + */ + meta?: Record; +}; + +export const export_ = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no+tag', ...options }); + +export const patchApiVbyApiVersionNoTag = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/no+tag', ...options }); + +export const import_ = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/no+tag', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const fooWow = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/no+tag', ...options }); + +export const apiVVersionODataControllerCount = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple/$count', ...options }); + +export const getApiVbyApiVersionSimpleOperation = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/simple:operation', ...options }); + +export const deleteCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/simple', ...options }); + +export const getCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/simple', ...options }); + +export const headCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).head({ url: '/api/v{api-version}/simple', ...options }); + +export const optionsCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).options({ url: '/api/v{api-version}/simple', ...options }); + +export const patchCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).patch({ url: '/api/v{api-version}/simple', ...options }); + +export const postCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/simple', ...options }); + +export const putCallWithoutParametersAndResponse = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/simple', ...options }); + +export const deleteFoo = (options: Options) => (options.client ?? client).delete({ url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', ...options }); + +export const callWithDescriptions = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/descriptions', ...options }); + +/** + * @deprecated + */ +export const deprecatedCall = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/parameters/deprecated', ...options }); + +export const callWithParameters = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/parameters/{parameterPath}', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const callWithWeirdParameterNames = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const getCallWithOptionalParam = (options: Options) => (options.client ?? client).get({ + url: '/api/v{api-version}/parameters', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const postCallWithOptionalParam = (options: Options) => (options.client ?? client).post({ + url: '/api/v{api-version}/parameters', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const postApiVbyApiVersionRequestBody = (options?: Options) => (options?.client ?? client).post({ + url: '/api/v{api-version}/requestBody', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options?.headers + } +}); + +export const postApiVbyApiVersionFormData = (options?: Options) => (options?.client ?? client).post({ + ...formDataBodySerializer, + url: '/api/v{api-version}/formData', + ...options, + headers: { + 'Content-Type': null, + ...options?.headers + } +}); + +export const callWithDefaultParameters = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/defaults', ...options }); + +export const callWithDefaultOptionalParameters = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/defaults', ...options }); + +export const callToTestOrderOfParams = (options: Options) => (options.client ?? client).put({ url: '/api/v{api-version}/defaults', ...options }); + +export const duplicateName = (options?: Options) => (options?.client ?? client).delete({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName2 = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName3 = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/duplicate', ...options }); + +export const duplicateName4 = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/duplicate', ...options }); + +export const callWithNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/no-content', ...options }); + +export const callWithResponseAndNoContentResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/response-and-no-content', ...options }); + +export const dummyA = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/a', ...options }); + +export const dummyB = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multiple-tags/b', ...options }); + +export const callWithResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/response', ...options }); + +export const callWithDuplicateResponses = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/response', ...options }); + +export const callWithResponses = (options?: Options) => (options?.client ?? client).put({ url: '/api/v{api-version}/response', ...options }); + +export const collectionFormat = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/collectionFormat', ...options }); + +export const types = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/types', ...options }); + +export const uploadFile = (options: Options) => (options.client ?? client).post({ + ...urlSearchParamsBodySerializer, + url: '/api/v{api-version}/upload', + ...options, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + ...options.headers + } +}); + +export const fileResponse = (options: Options) => (options.client ?? client).get({ url: '/api/v{api-version}/file/{id}', ...options }); + +export const complexTypes = (options: Options) => (options.client ?? client).get({ + querySerializer: { parameters: { parameterObject: { object: { style: 'form' } } } }, + url: '/api/v{api-version}/complex', + ...options +}); + +export const multipartResponse = (options?: Options) => (options?.client ?? client).get({ url: '/api/v{api-version}/multipart', ...options }); + +export const multipartRequest = (options?: Options) => (options?.client ?? client).post({ + ...formDataBodySerializer, + url: '/api/v{api-version}/multipart', + ...options, + headers: { + 'Content-Type': null, + ...options?.headers + } +}); + +export const complexParams = (options: Options) => (options.client ?? client).put({ + url: '/api/v{api-version}/complex/{id}', + ...options, + headers: { + 'Content-Type': 'application/json-patch+json', + ...options.headers + } +}); + +export const callWithResultFromHeader = (options?: Options) => (options?.client ?? client).post({ url: '/api/v{api-version}/header', ...options }); + +export const testErrorCode = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/error', ...options }); + +export const nonAsciiæøåÆøÅöôêÊ字符串 = (options: Options) => (options.client ?? client).post({ url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', ...options }); + +/** + * Login User + */ +export const putWithFormUrlEncoded = (options: Options) => (options.client ?? client).put({ + ...urlSearchParamsBodySerializer, + url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', + ...options, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + ...options.headers + } +}); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/types.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/types.gen.ts new file mode 100644 index 0000000000..d819316644 --- /dev/null +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/react-query/useQuery/types.gen.ts @@ -0,0 +1,2100 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type ClientOptions = { + baseUrl: 'http://localhost:3000/base' | (string & {}); +}; + +/** + * Model with number-only name + */ +export type _400 = string; + +/** + * External ref to shared model (A) + */ +export type ExternalRefA = ExternalSharedModel; + +/** + * External ref to shared model (B) + */ +export type ExternalRefB = ExternalSharedModel; + +/** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ +export type CamelCaseCommentWithBreaks = number; + +/** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ +export type CommentWithBreaks = number; + +/** + * Testing backticks in string: `backticks` and ```multiple backticks``` should work + */ +export type CommentWithBackticks = number; + +/** + * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work + */ +export type CommentWithBackticksAndQuotes = number; + +/** + * Testing slashes in string: \backwards\\\ and /forwards/// should work + */ +export type CommentWithSlashes = number; + +/** + * Testing expression placeholders in string: ${expression} should work + */ +export type CommentWithExpressionPlaceholders = number; + +/** + * Testing quotes in string: 'single quote''' and "double quotes""" should work + */ +export type CommentWithQuotes = number; + +/** + * Testing reserved characters in string: * inline * and ** inline ** should work + */ +export type CommentWithReservedCharacters = number; + +/** + * This is a simple number + */ +export type SimpleInteger = number; + +/** + * This is a simple boolean + */ +export type SimpleBoolean = boolean; + +/** + * This is a simple string + */ +export type SimpleString = string; + +/** + * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) + */ +export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; + +/** + * This is a simple file + */ +export type SimpleFile = Blob | File; + +/** + * This is a simple reference + */ +export type SimpleReference = ModelWithString; + +/** + * This is a simple string + */ +export type SimpleStringWithPattern = string | null; + +/** + * This is a simple enum with strings + */ +export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | '\'Single Quote\'' | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; + +export type EnumWithReplacedCharacters = '\'Single Quote\'' | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; + +/** + * This is a simple enum with numbers + */ +export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; + +/** + * Success=1,Warning=2,Error=3 + */ +export type EnumFromDescription = number; + +/** + * This is a simple enum with numbers + */ +export type EnumWithExtensions = 200 | 400 | 500; + +export type EnumWithXEnumNames = 0 | 1 | 2; + +/** + * This is a simple array with numbers + */ +export type ArrayWithNumbers = Array; + +/** + * This is a simple array with booleans + */ +export type ArrayWithBooleans = Array; + +/** + * This is a simple array with strings + */ +export type ArrayWithStrings = Array; + +/** + * This is a simple array with references + */ +export type ArrayWithReferences = Array; + +/** + * This is a simple array containing an array + */ +export type ArrayWithArray = Array>; + +/** + * This is a simple array with properties + */ +export type ArrayWithProperties = Array<{ + '16x16'?: CamelCaseCommentWithBreaks; + bar?: string; +}>; + +/** + * This is a simple array with any of properties + */ +export type ArrayWithAnyOfProperties = Array<{ + foo?: string; +} | { + bar?: string; +}>; + +export type AnyOfAnyAndNull = { + data?: unknown | null; +}; + +/** + * This is a simple array with any of properties + */ +export type AnyOfArrays = { + results?: Array<{ + foo?: string; + } | { + bar?: string; + }>; +}; + +/** + * This is a string dictionary + */ +export type DictionaryWithString = { + [key: string]: string; +}; + +export type DictionaryWithPropertiesAndAdditionalProperties = { + foo?: number; + bar?: boolean; + [key: string]: string | number | boolean | undefined; +}; + +/** + * This is a string reference + */ +export type DictionaryWithReference = { + [key: string]: ModelWithString; +}; + +/** + * This is a complex dictionary + */ +export type DictionaryWithArray = { + [key: string]: Array; +}; + +/** + * This is a string dictionary + */ +export type DictionaryWithDictionary = { + [key: string]: { + [key: string]: string; + }; +}; + +/** + * This is a complex dictionary + */ +export type DictionaryWithProperties = { + [key: string]: { + foo?: string; + bar?: string; + }; +}; + +/** + * This is a model with one number property + */ +export type ModelWithInteger = { + /** + * This is a simple number property + */ + prop?: number; +}; + +/** + * This is a model with one boolean property + */ +export type ModelWithBoolean = { + /** + * This is a simple boolean property + */ + prop?: boolean; +}; + +/** + * This is a model with one string property + */ +export type ModelWithString = { + /** + * This is a simple string property + */ + prop?: string; +}; + +/** + * This is a model with one string property + */ +export type ModelWithStringError = { + /** + * This is a simple string property + */ + prop?: string; +}; + +/** + * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) + */ +export type ModelFromZendesk = string; + +/** + * This is a model with one string property + */ +export type ModelWithNullableString = { + /** + * This is a simple string property + */ + nullableProp1?: string | null; + /** + * This is a simple string property + */ + nullableRequiredProp1: string | null; + /** + * This is a simple string property + */ + nullableProp2?: string | null; + /** + * This is a simple string property + */ + nullableRequiredProp2: string | null; + /** + * This is a simple enum with strings + */ + 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; +}; + +/** + * This is a model with one enum + */ +export type ModelWithEnum = { + /** + * This is a simple enum with strings + */ + 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; + /** + * These are the HTTP error code enums + */ + statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; + /** + * Simple boolean enum + */ + bool?: true; +}; + +/** + * This is a model with one enum with escaped name + */ +export type ModelWithEnumWithHyphen = { + /** + * Foo-Bar-Baz-Qux + */ + 'foo-bar-baz-qux'?: '3.0'; +}; + +/** + * This is a model with one enum + */ +export type ModelWithEnumFromDescription = { + /** + * Success=1,Warning=2,Error=3 + */ + test?: number; +}; + +/** + * This is a model with nested enums + */ +export type ModelWithNestedEnums = { + dictionaryWithEnum?: { + [key: string]: 'Success' | 'Warning' | 'Error'; + }; + dictionaryWithEnumFromDescription?: { + [key: string]: number; + }; + arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; + arrayWithDescription?: Array; + /** + * This is a simple enum with strings + */ + 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; +}; + +/** + * This is a model with one property containing a reference + */ +export type ModelWithReference = { + prop?: ModelWithProperties; +}; + +/** + * This is a model with one property containing an array + */ +export type ModelWithArrayReadOnlyAndWriteOnly = { + prop?: Array; + propWithFile?: Array; + propWithNumber?: Array; +}; + +/** + * This is a model with one property containing an array + */ +export type ModelWithArray = { + prop?: Array; + propWithFile?: Array; + propWithNumber?: Array; +}; + +/** + * This is a model with one property containing a dictionary + */ +export type ModelWithDictionary = { + prop?: { + [key: string]: string; + }; +}; + +/** + * This is a deprecated model with a deprecated property + * + * @deprecated + */ +export type DeprecatedModel = { + /** + * This is a deprecated property + * + * @deprecated + */ + prop?: string; +}; + +/** + * This is a model with one property containing a circular reference + */ +export type ModelWithCircularReference = { + prop?: ModelWithCircularReference; +}; + +/** + * This is a model with one property with a 'one of' relationship + */ +export type CompositionWithOneOf = { + propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; +}; + +/** + * This is a model with one property with a 'one of' relationship where the options are not $ref + */ +export type CompositionWithOneOfAnonymous = { + propA?: { + propA?: string; + } | string | number; +}; + +/** + * Circle + */ +export type ModelCircle = { + kind: string; + radius?: number; +}; + +/** + * Square + */ +export type ModelSquare = { + kind: string; + sideLength?: number; +}; + +/** + * This is a model with one property with a 'one of' relationship where the options are not $ref + */ +export type CompositionWithOneOfDiscriminator = ({ + kind: 'circle'; +} & ModelCircle) | ({ + kind: 'square'; +} & ModelSquare); + +/** + * This is a model with one property with a 'any of' relationship + */ +export type CompositionWithAnyOf = { + propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; +}; + +/** + * This is a model with one property with a 'any of' relationship where the options are not $ref + */ +export type CompositionWithAnyOfAnonymous = { + propA?: { + propA?: string; + } | string | number; +}; + +/** + * This is a model with nested 'any of' property with a type null + */ +export type CompositionWithNestedAnyAndTypeNull = { + propA?: Array | Array; +}; + +export type _3eNum1Период = 'Bird' | 'Dog'; + +export type ConstValue = 'ConstValue'; + +/** + * This is a model with one property with a 'any of' relationship where the options are not $ref + */ +export type CompositionWithNestedAnyOfAndNull = { + /** + * Scopes + */ + propA?: Array<_3eNum1Период | ConstValue> | null; +}; + +/** + * This is a model with one property with a 'one of' relationship + */ +export type CompositionWithOneOfAndNullable = { + propA?: { + boolean?: boolean; + } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; +}; + +/** + * This is a model that contains a simple dictionary within composition + */ +export type CompositionWithOneOfAndSimpleDictionary = { + propA?: boolean | { + [key: string]: number; + }; +}; + +/** + * This is a model that contains a dictionary of simple arrays within composition + */ +export type CompositionWithOneOfAndSimpleArrayDictionary = { + propA?: boolean | { + [key: string]: Array; + }; +}; + +/** + * This is a model that contains a dictionary of complex arrays (composited) within composition + */ +export type CompositionWithOneOfAndComplexArrayDictionary = { + propA?: boolean | { + [key: string]: Array; + }; +}; + +/** + * This is a model with one property with a 'all of' relationship + */ +export type CompositionWithAllOfAndNullable = { + propA?: ({ + boolean?: boolean; + } & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null; +}; + +/** + * This is a model with one property with a 'any of' relationship + */ +export type CompositionWithAnyOfAndNullable = { + propA?: { + boolean?: boolean; + } | ModelWithEnum | ModelWithArray | ModelWithDictionary | null; +}; + +/** + * This is a base model with two simple optional properties + */ +export type CompositionBaseModel = { + firstName?: string; + lastname?: string; +}; + +/** + * This is a model that extends the base model + */ +export type CompositionExtendedModel = CompositionBaseModel & { + age: number; + firstName: string; + lastname: string; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithProperties = { + required: string; + readonly requiredAndReadOnly: string; + requiredAndNullable: string | null; + string?: string; + number?: number; + boolean?: boolean; + reference?: ModelWithString; + 'property with space'?: string; + default?: string; + try?: string; + readonly '@namespace.string'?: string; + readonly '@namespace.integer'?: number; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithNestedProperties = { + readonly first: { + readonly second: { + readonly third: string | null; + } | null; + } | null; +}; + +/** + * This is a model with duplicated properties + */ +export type ModelWithDuplicateProperties = { + prop?: ModelWithString; +}; + +/** + * This is a model with ordered properties + */ +export type ModelWithOrderedProperties = { + zebra?: string; + apple?: string; + hawaii?: string; +}; + +/** + * This is a model with duplicated imports + */ +export type ModelWithDuplicateImports = { + propA?: ModelWithString; + propB?: ModelWithString; + propC?: ModelWithString; +}; + +/** + * This is a model that extends another model + */ +export type ModelThatExtends = ModelWithString & { + propExtendsA?: string; + propExtendsB?: ModelWithString; +}; + +/** + * This is a model that extends another model + */ +export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { + propExtendsC?: string; + propExtendsD?: ModelWithString; +}; + +/** + * This is a model that contains a some patterns + */ +export type ModelWithPattern = { + key: string; + name: string; + readonly enabled?: boolean; + readonly modified?: string; + id?: string; + text?: string; + patternWithSingleQuotes?: string; + patternWithNewline?: string; + patternWithBacktick?: string; + patternWithUnicode?: string; +}; + +export type File = { + /** + * Id + */ + readonly id?: string; + /** + * Updated at + */ + readonly updated_at?: string; + /** + * Created at + */ + readonly created_at?: string; + /** + * Mime + */ + mime: string; + /** + * File + */ + readonly file?: string; +}; + +export type Default = { + name?: string; +}; + +export type Pageable = { + page?: number; + size?: number; + sort?: Array; +}; + +/** + * This is a free-form object without additionalProperties. + */ +export type FreeFormObjectWithoutAdditionalProperties = { + [key: string]: unknown; +}; + +/** + * This is a free-form object with additionalProperties: true. + */ +export type FreeFormObjectWithAdditionalPropertiesEqTrue = { + [key: string]: unknown; +}; + +/** + * This is a free-form object with additionalProperties: {}. + */ +export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { + [key: string]: unknown; +}; + +export type ModelWithConst = { + String?: 'String'; + number?: 0; + null?: null; + withType?: 'Some string'; +}; + +/** + * This is a model with one property and additionalProperties: true + */ +export type ModelWithAdditionalPropertiesEqTrue = { + /** + * This is a simple string property + */ + prop?: string; + [key: string]: unknown; +}; + +export type NestedAnyOfArraysNullable = { + nullableArray?: Array | null; +}; + +export type CompositionWithOneOfAndProperties = ({ + foo: SimpleParameter; +} | { + bar: NonAsciiStringæøåÆøÅöôêÊ字符串; +}) & { + baz: number | null; + qux: number; +}; + +/** + * An object that can be null + */ +export type NullableObject = { + foo?: string; +} | null; + +/** + * Some % character + */ +export type CharactersInDescription = string; + +export type ModelWithNullableObject = { + data?: NullableObject; +}; + +/** + * An object with additional properties that can be null (anyOf ref + null) + */ +export type ModelWithAdditionalPropertiesRef = { + [key: string]: NullableObject | null; +}; + +export type ModelWithOneOfEnum = { + foo: 'Bar'; +} | { + foo: 'Baz'; +} | { + foo: 'Qux'; +} | { + content: string; + foo: 'Quux'; +} | { + content: [ + string, + string + ]; + foo: 'Corge'; +}; + +export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; + +export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; + +export type ModelWithNestedArrayEnumsData = { + foo?: Array; + bar?: Array; +}; + +export type ModelWithNestedArrayEnums = { + array_strings?: Array; + data?: ModelWithNestedArrayEnumsData; +}; + +export type ModelWithNestedCompositionEnums = { + foo?: ModelWithNestedArrayEnumsDataFoo; +}; + +export type ModelWithReadOnlyAndWriteOnly = { + foo: string; + readonly bar: string; +}; + +export type ModelWithConstantSizeArray = [ + number, + number +]; + +export type ModelWithAnyOfConstantSizeArray = [ + number | string, + number | string, + number | string +]; + +export type ModelWithPrefixItemsConstantSizeArray = [ + ModelWithInteger, + number | string, + string +]; + +export type ModelWithAnyOfConstantSizeArrayNullable = [ + number | null | string, + number | null | string, + number | null | string +]; + +export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ + number | Import, + number | Import +]; + +export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ + number & string, + number & string +]; + +export type ModelWithNumericEnumUnion = { + /** + * Период + */ + value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; +}; + +/** + * Some description with `back ticks` + */ +export type ModelWithBackticksInDescription = { + /** + * The template `that` should be used for parsing and importing the contents of the CSV file. + * + *

There is one placeholder currently supported:

  • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

Example of a correct JSON template:

+ *
+     * [
+     * {
+     * "resourceType": "Asset",
+     * "identifier": {
+     * "name": "${1}",
+     * "domain": {
+     * "name": "${2}",
+     * "community": {
+     * "name": "Some Community"
+     * }
+     * }
+     * },
+     * "attributes" : {
+     * "00000000-0000-0000-0000-000000003115" : [ {
+     * "value" : "${3}"
+     * } ],
+     * "00000000-0000-0000-0000-000000000222" : [ {
+     * "value" : "${4}"
+     * } ]
+     * }
+     * }
+     * ]
+     * 
+ */ + template?: string; +}; + +export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { + baz: number | null; + qux: number; +}; + +/** + * Model used to test deduplication strategy (unused) + */ +export type ParameterSimpleParameterUnused = string; + +/** + * Model used to test deduplication strategy + */ +export type PostServiceWithEmptyTagResponse = string; + +/** + * Model used to test deduplication strategy + */ +export type PostServiceWithEmptyTagResponse2 = string; + +/** + * Model used to test deduplication strategy + */ +export type DeleteFooData = string; + +/** + * Model used to test deduplication strategy + */ +export type DeleteFooData2 = string; + +/** + * Model with restricted keyword name + */ +export type Import = string; + +export type SchemaWithFormRestrictedKeys = { + description?: string; + 'x-enum-descriptions'?: string; + 'x-enum-varnames'?: string; + 'x-enumNames'?: string; + title?: string; + object?: { + description?: string; + 'x-enum-descriptions'?: string; + 'x-enum-varnames'?: string; + 'x-enumNames'?: string; + title?: string; + }; + array?: Array<{ + description?: string; + 'x-enum-descriptions'?: string; + 'x-enum-varnames'?: string; + 'x-enumNames'?: string; + title?: string; + }>; +}; + +/** + * This schema was giving PascalCase transformations a hard time + */ +export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { + /** + * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. + */ + preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; +}; + +/** + * This schema was giving PascalCase transformations a hard time + */ +export type IoK8sApimachineryPkgApisMetaV1Preconditions = { + /** + * Specifies the target ResourceVersion + */ + resourceVersion?: string; + /** + * Specifies the target UID. + */ + uid?: string; +}; + +export type AdditionalPropertiesUnknownIssue = { + [key: string]: string | number; +}; + +export type AdditionalPropertiesUnknownIssue2 = { + [key: string]: string | number; +}; + +export type AdditionalPropertiesUnknownIssue3 = string & { + entries: { + [key: string]: AdditionalPropertiesUnknownIssue; + }; +}; + +export type AdditionalPropertiesIntegerIssue = { + value: number; + [key: string]: number; +}; + +export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; + +export type GenericSchemaDuplicateIssue1SystemBoolean = { + item?: boolean; + error?: string | null; + readonly hasError?: boolean; + data?: { + [key: string]: never; + }; +}; + +export type GenericSchemaDuplicateIssue1SystemString = { + item?: string | null; + error?: string | null; + readonly hasError?: boolean; +}; + +export type ExternalSharedModel = { + id: string; + name?: string; +}; + +/** + * This is a model with one property containing a reference + */ +export type ModelWithReferenceWritable = { + prop?: ModelWithPropertiesWritable; +}; + +/** + * This is a model with one property containing an array + */ +export type ModelWithArrayReadOnlyAndWriteOnlyWritable = { + prop?: Array; + propWithFile?: Array; + propWithNumber?: Array; +}; + +/** + * This is a model with one nested property + */ +export type ModelWithPropertiesWritable = { + required: string; + requiredAndNullable: string | null; + string?: string; + number?: number; + boolean?: boolean; + reference?: ModelWithString; + 'property with space'?: string; + default?: string; + try?: string; +}; + +/** + * This is a model that contains a some patterns + */ +export type ModelWithPatternWritable = { + key: string; + name: string; + id?: string; + text?: string; + patternWithSingleQuotes?: string; + patternWithNewline?: string; + patternWithBacktick?: string; + patternWithUnicode?: string; +}; + +export type FileWritable = { + /** + * Mime + */ + mime: string; +}; + +export type ModelWithReadOnlyAndWriteOnlyWritable = { + foo: string; + baz: string; +}; + +export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsWritable = [ + number | Import, + number | Import +]; + +export type AdditionalPropertiesUnknownIssueWritable = { + [key: string]: string | number; +}; + +export type OneOfAllOfIssueWritable = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; + +export type GenericSchemaDuplicateIssue1SystemBooleanWritable = { + item?: boolean; + error?: string | null; + data?: { + [key: string]: never; + }; +}; + +export type GenericSchemaDuplicateIssue1SystemStringWritable = { + item?: string | null; + error?: string | null; +}; + +/** + * This is a reusable parameter + */ +export type SimpleParameter = string; + +/** + * Parameter with illegal characters + */ +export type XFooBar = ModelWithString; + +/** + * A reusable request body + */ +export type SimpleRequestBody = ModelWithString; + +/** + * A reusable request body + */ +export type SimpleFormData = ModelWithString; + +export type ExportData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type PatchApiVbyApiVersionNoTagData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type PatchApiVbyApiVersionNoTagResponses = { + /** + * OK + */ + default: unknown; +}; + +export type ImportData = { + body: ModelWithReadOnlyAndWriteOnlyWritable | ModelWithArrayReadOnlyAndWriteOnlyWritable; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type ImportResponses = { + /** + * Success + */ + 200: ModelFromZendesk; + /** + * Default success response + */ + default: ModelWithReadOnlyAndWriteOnly; +}; + +export type ImportResponse = ImportResponses[keyof ImportResponses]; + +export type FooWowData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no+tag'; +}; + +export type FooWowResponses = { + /** + * OK + */ + default: unknown; +}; + +export type ApiVVersionODataControllerCountData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple/$count'; +}; + +export type ApiVVersionODataControllerCountResponses = { + /** + * Success + */ + 200: ModelFromZendesk; +}; + +export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; + +export type GetApiVbyApiVersionSimpleOperationData = { + body?: never; + path: { + /** + * foo in method + */ + foo_param: string; + }; + query?: never; + url: '/api/v{api-version}/simple:operation'; +}; + +export type GetApiVbyApiVersionSimpleOperationErrors = { + /** + * Default error response + */ + default: ModelWithBoolean; +}; + +export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; + +export type GetApiVbyApiVersionSimpleOperationResponses = { + /** + * Response is a simple number + */ + 200: number; +}; + +export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; + +export type DeleteCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type GetCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type HeadCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type OptionsCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PatchCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PostCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type PutCallWithoutParametersAndResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/simple'; +}; + +export type DeleteFooData3 = { + body?: never; + headers: { + /** + * Parameter with illegal characters + */ + 'x-Foo-Bar': ModelWithString; + }; + path: { + /** + * foo in method + */ + foo_param: string; + /** + * bar in method + */ + BarParam: string; + }; + query?: never; + url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; +}; + +export type CallWithDescriptionsData = { + body?: never; + path?: never; + query?: { + /** + * Testing multiline comments in string: First line + * Second line + * + * Fourth line + */ + parameterWithBreaks?: string; + /** + * Testing backticks in string: `backticks` and ```multiple backticks``` should work + */ + parameterWithBackticks?: string; + /** + * Testing slashes in string: \backwards\\\ and /forwards/// should work + */ + parameterWithSlashes?: string; + /** + * Testing expression placeholders in string: ${expression} should work + */ + parameterWithExpressionPlaceholders?: string; + /** + * Testing quotes in string: 'single quote''' and "double quotes""" should work + */ + parameterWithQuotes?: string; + /** + * Testing reserved characters in string: * inline * and ** inline ** should work + */ + parameterWithReservedCharacters?: string; + }; + url: '/api/v{api-version}/descriptions'; +}; + +export type DeprecatedCallData = { + body?: never; + headers: { + /** + * This parameter is deprecated + * + * @deprecated + */ + parameter: DeprecatedModel | null; + }; + path?: never; + query?: never; + url: '/api/v{api-version}/parameters/deprecated'; +}; + +export type CallWithParametersData = { + /** + * This is the parameter that goes into the body + */ + body: { + [key: string]: unknown; + } | null; + headers: { + /** + * This is the parameter that goes into the header + */ + parameterHeader: string | null; + }; + path: { + /** + * This is the parameter that goes into the path + */ + parameterPath: string | null; + /** + * api-version should be required in standalone clients + */ + 'api-version': string | null; + }; + query: { + foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; + foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; + /** + * This is the parameter that goes into the query params + */ + cursor: string | null; + }; + url: '/api/v{api-version}/parameters/{parameterPath}'; +}; + +export type CallWithWeirdParameterNamesData = { + /** + * This is the parameter that goes into the body + */ + body: ModelWithString | null; + headers: { + /** + * This is the parameter that goes into the request header + */ + 'parameter.header': string | null; + }; + path: { + /** + * This is the parameter that goes into the path + */ + 'parameter.path.1'?: string; + /** + * This is the parameter that goes into the path + */ + 'parameter-path-2'?: string; + /** + * This is the parameter that goes into the path + */ + 'PARAMETER-PATH-3'?: string; + /** + * api-version should be required in standalone clients + */ + 'api-version': string | null; + }; + query: { + /** + * This is the parameter with a reserved keyword + */ + default?: string; + /** + * This is the parameter that goes into the request query params + */ + 'parameter-query': string | null; + }; + url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; +}; + +export type GetCallWithOptionalParamData = { + /** + * This is a required parameter + */ + body: ModelWithOneOfEnum; + path?: never; + query?: { + /** + * This is an optional parameter + */ + page?: number; + }; + url: '/api/v{api-version}/parameters'; +}; + +export type PostCallWithOptionalParamData = { + /** + * This is an optional parameter + */ + body?: { + offset?: number | null; + }; + path?: never; + query: { + /** + * This is a required parameter + */ + parameter: Pageable; + }; + url: '/api/v{api-version}/parameters'; +}; + +export type PostCallWithOptionalParamResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Success + */ + 204: void; +}; + +export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; + +export type PostApiVbyApiVersionRequestBodyData = { + /** + * A reusable request body + */ + body?: SimpleRequestBody; + path?: never; + query?: { + /** + * This is a reusable parameter + */ + parameter?: string; + }; + url: '/api/v{api-version}/requestBody'; +}; + +export type PostApiVbyApiVersionFormDataData = { + /** + * A reusable request body + */ + body?: SimpleFormData; + path?: never; + query?: { + /** + * This is a reusable parameter + */ + parameter?: string; + }; + url: '/api/v{api-version}/formData'; +}; + +export type CallWithDefaultParametersData = { + body?: never; + path?: never; + query?: { + /** + * This is a simple string with default value + */ + parameterString?: string | null; + /** + * This is a simple number with default value + */ + parameterNumber?: number | null; + /** + * This is a simple boolean with default value + */ + parameterBoolean?: boolean | null; + /** + * This is a simple enum with default value + */ + parameterEnum?: 'Success' | 'Warning' | 'Error'; + /** + * This is a simple model with default value + */ + parameterModel?: ModelWithString | null; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type CallWithDefaultOptionalParametersData = { + body?: never; + path?: never; + query?: { + /** + * This is a simple string that is optional with default value + */ + parameterString?: string; + /** + * This is a simple number that is optional with default value + */ + parameterNumber?: number; + /** + * This is a simple boolean that is optional with default value + */ + parameterBoolean?: boolean; + /** + * This is a simple enum that is optional with default value + */ + parameterEnum?: 'Success' | 'Warning' | 'Error'; + /** + * This is a simple model that is optional with default value + */ + parameterModel?: ModelWithString; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type CallToTestOrderOfParamsData = { + body?: never; + path?: never; + query: { + /** + * This is a optional string with default + */ + parameterOptionalStringWithDefault?: string; + /** + * This is a optional string with empty default + */ + parameterOptionalStringWithEmptyDefault?: string; + /** + * This is a optional string with no default + */ + parameterOptionalStringWithNoDefault?: string; + /** + * This is a string with default + */ + parameterStringWithDefault: string; + /** + * This is a string with empty default + */ + parameterStringWithEmptyDefault: string; + /** + * This is a string with no default + */ + parameterStringWithNoDefault: string; + /** + * This is a string that can be null with no default + */ + parameterStringNullableWithNoDefault?: string | null; + /** + * This is a string that can be null with default + */ + parameterStringNullableWithDefault?: string | null; + }; + url: '/api/v{api-version}/defaults'; +}; + +export type DuplicateNameData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName2Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName3Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type DuplicateName4Data = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/duplicate'; +}; + +export type CallWithNoContentResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/no-content'; +}; + +export type CallWithNoContentResponseResponses = { + /** + * Success + */ + 204: void; +}; + +export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; + +export type CallWithResponseAndNoContentResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/response-and-no-content'; +}; + +export type CallWithResponseAndNoContentResponseResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Success + */ + 204: void; +}; + +export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; + +export type DummyAData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/a'; +}; + +export type DummyAResponses = { + 200: _400; +}; + +export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; + +export type DummyBData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multiple-tags/b'; +}; + +export type DummyBResponses = { + /** + * Success + */ + 204: void; +}; + +export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; + +export type CallWithResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithResponseResponses = { + default: Import; +}; + +export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; + +export type CallWithDuplicateResponsesData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithDuplicateResponsesErrors = { + /** + * Message for 500 error + */ + 500: ModelWithStringError; + /** + * Message for 501 error + */ + 501: ModelWithStringError; + /** + * Message for 502 error + */ + 502: ModelWithStringError; + /** + * Message for 4XX errors + */ + '4XX': DictionaryWithArray; + /** + * Default error response + */ + default: ModelWithBoolean; +}; + +export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; + +export type CallWithDuplicateResponsesResponses = { + /** + * Message for 200 response + */ + 200: ModelWithBoolean & ModelWithInteger; + /** + * Message for 201 response + */ + 201: ModelWithString; + /** + * Message for 202 response + */ + 202: ModelWithString; +}; + +export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; + +export type CallWithResponsesData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/response'; +}; + +export type CallWithResponsesErrors = { + /** + * Message for 500 error + */ + 500: ModelWithStringError; + /** + * Message for 501 error + */ + 501: ModelWithStringError; + /** + * Message for 502 error + */ + 502: ModelWithStringError; + /** + * Message for default response + */ + default: ModelWithStringError; +}; + +export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; + +export type CallWithResponsesResponses = { + /** + * Message for 200 response + */ + 200: { + readonly '@namespace.string'?: string; + readonly '@namespace.integer'?: number; + readonly value?: Array; + }; + /** + * Message for 201 response + */ + 201: ModelThatExtends; + /** + * Message for 202 response + */ + 202: ModelThatExtendsExtends; +}; + +export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; + +export type CollectionFormatData = { + body?: never; + path?: never; + query: { + /** + * This is an array parameter that is sent as csv format (comma-separated values) + */ + parameterArrayCSV: Array | null; + /** + * This is an array parameter that is sent as ssv format (space-separated values) + */ + parameterArraySSV: Array | null; + /** + * This is an array parameter that is sent as tsv format (tab-separated values) + */ + parameterArrayTSV: Array | null; + /** + * This is an array parameter that is sent as pipes format (pipe-separated values) + */ + parameterArrayPipes: Array | null; + /** + * This is an array parameter that is sent as multi format (multiple parameter instances) + */ + parameterArrayMulti: Array | null; + }; + url: '/api/v{api-version}/collectionFormat'; +}; + +export type TypesData = { + body?: never; + path?: { + /** + * This is a number parameter + */ + id?: number; + }; + query: { + /** + * This is a number parameter + */ + parameterNumber: number; + /** + * This is a string parameter + */ + parameterString: string | null; + /** + * This is a boolean parameter + */ + parameterBoolean: boolean | null; + /** + * This is an object parameter + */ + parameterObject: { + [key: string]: unknown; + } | null; + /** + * This is an array parameter + */ + parameterArray: Array | null; + /** + * This is a dictionary parameter + */ + parameterDictionary: { + [key: string]: unknown; + } | null; + /** + * This is an enum parameter + */ + parameterEnum: 'Success' | 'Warning' | 'Error' | null; + }; + url: '/api/v{api-version}/types'; +}; + +export type TypesResponses = { + /** + * Response is a simple number + */ + 200: number; + /** + * Response is a simple string + */ + 201: string; + /** + * Response is a simple boolean + */ + 202: boolean; + /** + * Response is a simple object + */ + 203: { + [key: string]: unknown; + }; +}; + +export type TypesResponse = TypesResponses[keyof TypesResponses]; + +export type UploadFileData = { + body: Blob | File; + path: { + /** + * api-version should be required in standalone clients + */ + 'api-version': string | null; + }; + query?: never; + url: '/api/v{api-version}/upload'; +}; + +export type UploadFileResponses = { + 200: boolean; +}; + +export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; + +export type FileResponseData = { + body?: never; + path: { + id: string; + /** + * api-version should be required in standalone clients + */ + 'api-version': string; + }; + query?: never; + url: '/api/v{api-version}/file/{id}'; +}; + +export type FileResponseResponses = { + /** + * Success + */ + 200: Blob | File; +}; + +export type FileResponseResponse = FileResponseResponses[keyof FileResponseResponses]; + +export type ComplexTypesData = { + body?: never; + path?: never; + query: { + /** + * Parameter containing object + */ + parameterObject: { + first?: { + second?: { + third?: string; + }; + }; + }; + /** + * Parameter containing reference + */ + parameterReference: ModelWithString; + }; + url: '/api/v{api-version}/complex'; +}; + +export type ComplexTypesErrors = { + /** + * 400 `server` error + */ + 400: unknown; + /** + * 500 server error + */ + 500: unknown; +}; + +export type ComplexTypesResponses = { + /** + * Successful response + */ + 200: Array; +}; + +export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; + +export type MultipartResponseData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/multipart'; +}; + +export type MultipartResponseResponses = { + /** + * OK + */ + 200: { + file?: Blob | File; + metadata?: { + foo?: string; + bar?: string; + }; + }; +}; + +export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; + +export type MultipartRequestData = { + body?: { + content?: Blob | File; + data?: ModelWithString | null; + }; + path?: never; + query?: never; + url: '/api/v{api-version}/multipart'; +}; + +export type ComplexParamsData = { + body?: { + readonly key: string | null; + name: string | null; + enabled?: boolean; + type: 'Monkey' | 'Horse' | 'Bird'; + listOfModels?: Array | null; + listOfStrings?: Array | null; + parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; + readonly user?: { + readonly id?: number; + readonly name?: string | null; + }; + }; + path: { + id: number; + /** + * api-version should be required in standalone clients + */ + 'api-version': string; + }; + query?: never; + url: '/api/v{api-version}/complex/{id}'; +}; + +export type ComplexParamsResponses = { + /** + * Success + */ + 200: ModelWithString; +}; + +export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; + +export type CallWithResultFromHeaderData = { + body?: never; + path?: never; + query?: never; + url: '/api/v{api-version}/header'; +}; + +export type CallWithResultFromHeaderErrors = { + /** + * 400 server error + */ + 400: unknown; + /** + * 500 server error + */ + 500: unknown; +}; + +export type CallWithResultFromHeaderResponses = { + /** + * Successful response + */ + 200: unknown; +}; + +export type TestErrorCodeData = { + body?: never; + path?: never; + query: { + /** + * Status code to return + */ + status: number; + }; + url: '/api/v{api-version}/error'; +}; + +export type TestErrorCodeErrors = { + /** + * Custom message: Internal Server Error + */ + 500: unknown; + /** + * Custom message: Not Implemented + */ + 501: unknown; + /** + * Custom message: Bad Gateway + */ + 502: unknown; + /** + * Custom message: Service Unavailable + */ + 503: unknown; +}; + +export type TestErrorCodeResponses = { + /** + * Custom message: Successful response + */ + 200: unknown; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Data = { + body?: never; + path?: never; + query: { + /** + * Dummy input param + */ + nonAsciiParamæøåÆØÅöôêÊ: number; + }; + url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { + /** + * Successful response + */ + 200: Array; +}; + +export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; + +export type PutWithFormUrlEncodedData = { + body: ArrayWithStrings; + path?: never; + query?: never; + url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; +}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/asClass/@tanstack/solid-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/asClass/@tanstack/solid-query.gen.ts index d5594064cc..4c3bc16520 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/asClass/@tanstack/solid-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/asClass/@tanstack/solid-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/solid-query'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/solid-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooOptions = (options?: Options) => queryOptions>): MutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutMutation = (options?: Partial>): Mutation export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarOptions = (options?: Options) => queryOptio throwOnError: true }); return data; - }, - queryKey: getFooBarQueryKey(options) + }), + queryKey: getFooBarQueryKey(resolveOptions(options)) }); export const fooBarPostMutation = (options?: Partial>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/axios/@tanstack/solid-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/axios/@tanstack/solid-query.gen.ts index 203534a865..d69126c7cb 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/axios/@tanstack/solid-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/axios/@tanstack/solid-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/solid-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions, skipToken } from '@tanstack/solid-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; @@ -40,10 +40,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -51,8 +55,8 @@ export const exportOptions = (options?: Options) => queryOptions>): MutationOptions, Options> => { @@ -99,8 +103,8 @@ export const fooWowMutation = (options?: Partial>): Mutation export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -108,14 +112,14 @@ export const apiVVersionODataControllerCountOptions = (options?: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -123,8 +127,8 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options>): MutationOptions, Options> => { @@ -143,8 +147,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -152,8 +156,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): MutationOptions, Options> => { @@ -273,8 +277,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -282,8 +286,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -317,10 +321,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -335,8 +339,8 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options>): MutationOptions, Options> => { @@ -383,8 +387,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -392,8 +396,8 @@ export const callWithDefaultParametersOptions = (options?: Options>): MutationOptions, Options> => { @@ -440,8 +444,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -449,8 +453,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions, Options> => { @@ -483,8 +487,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -492,14 +496,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -507,14 +511,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions, DummyAResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -522,14 +526,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions, DummyBResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -537,14 +541,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -552,8 +556,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions, Options> => { @@ -586,8 +590,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -595,14 +599,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions, TypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -610,8 +614,8 @@ export const typesOptions = (options: Options) => queryOptions>): MutationOptions, Options> => { @@ -630,8 +634,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions, FileResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -639,14 +643,14 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions, ComplexTypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -654,14 +658,14 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions, MultipartResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -669,8 +673,8 @@ export const multipartResponseOptions = (options?: Options>): MutationOptions, Options> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/fetch/@tanstack/solid-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/fetch/@tanstack/solid-query.gen.ts index 358caac28f..5bbeeb813b 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/fetch/@tanstack/solid-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/fetch/@tanstack/solid-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/solid-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions, skipToken } from '@tanstack/solid-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const exportOptions = (options?: Options) => queryOptions>): MutationOptions> => { @@ -98,8 +102,8 @@ export const fooWowMutation = (options?: Partial>): Mutation export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -107,14 +111,14 @@ export const apiVVersionODataControllerCountOptions = (options?: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -122,8 +126,8 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options>): MutationOptions> => { @@ -142,8 +146,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -151,8 +155,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): MutationOptions> => { @@ -272,8 +276,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -281,8 +285,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -316,10 +320,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -334,8 +338,8 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options>): MutationOptions> => { @@ -382,8 +386,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -391,8 +395,8 @@ export const callWithDefaultParametersOptions = (options?: Options>): MutationOptions> => { @@ -439,8 +443,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -448,8 +452,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions> => { @@ -482,8 +486,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -491,14 +495,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -506,14 +510,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -521,14 +525,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -536,14 +540,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -551,8 +555,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions> => { @@ -585,8 +589,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -594,14 +598,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -609,8 +613,8 @@ export const typesOptions = (options: Options) => queryOptions>): MutationOptions> => { @@ -629,8 +633,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -638,14 +642,14 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -653,14 +657,14 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -668,8 +672,8 @@ export const multipartResponseOptions = (options?: Options>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/name-builder/@tanstack/solid-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/name-builder/@tanstack/solid-query.gen.ts index ba1febdda4..c7ec98152f 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/name-builder/@tanstack/solid-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/solid-query/name-builder/@tanstack/solid-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/solid-query'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/solid-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooD = (options?: Options) => createQueryKey('getFoo', options); -export const getFooE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooE = (options?: Options) => queryOptions>): MutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutC = (options?: Partial>): MutationOptions export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarE = (options?: Options) => queryOptions>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/asClass/@tanstack/svelte-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/asClass/@tanstack/svelte-query.gen.ts index 3e29275971..af19b9b3eb 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/asClass/@tanstack/svelte-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/asClass/@tanstack/svelte-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/svelte-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooOptions = (options?: Options) => queryOptions>): MutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutMutation = (options?: Partial>): Mutation export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarOptions = (options?: Options) => queryOptio throwOnError: true }); return data; - }, - queryKey: getFooBarQueryKey(options) + }), + queryKey: getFooBarQueryKey(resolveOptions(options)) }); export const fooBarPostMutation = (options?: Partial>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/axios/@tanstack/svelte-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/axios/@tanstack/svelte-query.gen.ts index 9e78e66d27..58d7b73904 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/axios/@tanstack/svelte-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/axios/@tanstack/svelte-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions, skipToken } from '@tanstack/svelte-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; @@ -40,10 +40,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -51,8 +55,8 @@ export const exportOptions = (options?: Options) => queryOptions>): MutationOptions, Options> => { @@ -99,8 +103,8 @@ export const fooWowMutation = (options?: Partial>): Mutation export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -108,14 +112,14 @@ export const apiVVersionODataControllerCountOptions = (options?: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -123,8 +127,8 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options>): MutationOptions, Options> => { @@ -143,8 +147,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -152,8 +156,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): MutationOptions, Options> => { @@ -273,8 +277,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -282,8 +286,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -317,10 +321,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -335,8 +339,8 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options>): MutationOptions, Options> => { @@ -383,8 +387,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -392,8 +396,8 @@ export const callWithDefaultParametersOptions = (options?: Options>): MutationOptions, Options> => { @@ -440,8 +444,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -449,8 +453,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions, Options> => { @@ -483,8 +487,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -492,14 +496,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -507,14 +511,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions, DummyAResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -522,14 +526,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions, DummyBResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -537,14 +541,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -552,8 +556,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions, Options> => { @@ -586,8 +590,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -595,14 +599,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions, TypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -610,8 +614,8 @@ export const typesOptions = (options: Options) => queryOptions>): MutationOptions, Options> => { @@ -630,8 +634,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions, FileResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -639,14 +643,14 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions, ComplexTypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -654,14 +658,14 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions, MultipartResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -669,8 +673,8 @@ export const multipartResponseOptions = (options?: Options>): MutationOptions, Options> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/fetch/@tanstack/svelte-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/fetch/@tanstack/svelte-query.gen.ts index 7e81c37313..befa35b62f 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/fetch/@tanstack/svelte-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/fetch/@tanstack/svelte-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, type MutationOptions, queryOptions, skipToken } from '@tanstack/svelte-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const exportOptions = (options?: Options) => queryOptions>): MutationOptions> => { @@ -98,8 +102,8 @@ export const fooWowMutation = (options?: Partial>): Mutation export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -107,14 +111,14 @@ export const apiVVersionODataControllerCountOptions = (options?: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -122,8 +126,8 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options>): MutationOptions> => { @@ -142,8 +146,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -151,8 +155,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): MutationOptions> => { @@ -272,8 +276,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -281,8 +285,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -316,10 +320,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -334,8 +338,8 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options>): MutationOptions> => { @@ -382,8 +386,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -391,8 +395,8 @@ export const callWithDefaultParametersOptions = (options?: Options>): MutationOptions> => { @@ -439,8 +443,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -448,8 +452,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): MutationOptions> => { @@ -482,8 +486,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -491,14 +495,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -506,14 +510,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -521,14 +525,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -536,14 +540,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -551,8 +555,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): MutationOptions> => { @@ -585,8 +589,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -594,14 +598,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -609,8 +613,8 @@ export const typesOptions = (options: Options) => queryOptions>): MutationOptions> => { @@ -629,8 +633,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -638,14 +642,14 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -653,14 +657,14 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -668,8 +672,8 @@ export const multipartResponseOptions = (options?: Options>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/name-builder/@tanstack/svelte-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/name-builder/@tanstack/svelte-query.gen.ts index 6a831b5b3e..ad8c29d041 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/name-builder/@tanstack/svelte-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/svelte-query/name-builder/@tanstack/svelte-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type MutationOptions, queryOptions } from '@tanstack/svelte-query'; +import { type DefaultError, type MutationOptions, queryOptions, skipToken } from '@tanstack/svelte-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooD = (options?: Options) => createQueryKey('getFoo', options); -export const getFooE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooE = (options?: Options) => queryOptions>): MutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutC = (options?: Partial>): MutationOptions export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarE = (options?: Options) => queryOptions>): MutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/asClass/@tanstack/vue-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/asClass/@tanstack/vue-query.gen.ts index 2e82ca3558..317e2a873f 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/asClass/@tanstack/vue-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/asClass/@tanstack/vue-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions } from '@tanstack/vue-query'; import { client } from '../client.gen'; import { BarBazService, BarService, FooBazService, FooService, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooQueryKey = (options?: Options) => createQueryKey('getFoo', options); -export const getFooOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await FooBazService.getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooOptions = (options?: Options) => queryOptions>): UseMutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutMutation = (options?: Partial>): UseMutat export const getFooBarQueryKey = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await BarBazService.getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarOptions = (options?: Options) => queryOptio throwOnError: true }); return data; - }, - queryKey: getFooBarQueryKey(options) + }), + queryKey: getFooBarQueryKey(resolveOptions(options)) }); export const fooBarPostMutation = (options?: Partial>): UseMutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/axios/@tanstack/vue-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/axios/@tanstack/vue-query.gen.ts index f839621a3d..69b570cb63 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/axios/@tanstack/vue-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/axios/@tanstack/vue-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, skipToken, type UseMutationOptions } from '@tanstack/vue-query'; import type { AxiosError } from 'axios'; import { client } from '../client.gen'; @@ -40,10 +40,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -51,8 +55,8 @@ export const exportOptions = (options?: Options) => queryOptions>): UseMutationOptions, Options> => { @@ -99,8 +103,8 @@ export const fooWowMutation = (options?: Partial>): UseMutat export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions, ApiVVersionODataControllerCountResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -108,14 +112,14 @@ export const apiVVersionODataControllerCountOptions = (options?: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions, GetApiVbyApiVersionSimpleOperationResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -123,8 +127,8 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options>): UseMutationOptions, Options> => { @@ -143,8 +147,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -152,8 +156,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): UseMutationOptions, Options> => { @@ -273,8 +277,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -282,8 +286,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -317,10 +321,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, InfiniteData, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -335,8 +339,8 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options>): UseMutationOptions, Options> => { @@ -383,8 +387,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -392,8 +396,8 @@ export const callWithDefaultParametersOptions = (options?: Options>): UseMutationOptions, Options> => { @@ -440,8 +444,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -449,8 +453,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions, Options> => { @@ -483,8 +487,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -492,14 +496,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseAndNoContentResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -507,14 +511,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions, DummyAResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions, DummyAResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -522,14 +526,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions, DummyBResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions, DummyBResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -537,14 +541,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions, CallWithResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions, CallWithResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -552,8 +556,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions, Options> => { @@ -586,8 +590,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions, unknown, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions, unknown, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -595,14 +599,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions, TypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions, TypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -610,8 +614,8 @@ export const typesOptions = (options: Options) => queryOptions>): UseMutationOptions, Options> => { @@ -630,8 +634,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions, FileResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions, FileResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -639,14 +643,14 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions, ComplexTypesResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions, ComplexTypesResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -654,14 +658,14 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions, MultipartResponseResponse, ReturnType>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions, MultipartResponseResponse, ReturnType>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -669,8 +673,8 @@ export const multipartResponseOptions = (options?: Options>): UseMutationOptions, Options> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/fetch/@tanstack/vue-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/fetch/@tanstack/vue-query.gen.ts index bbcab4d5a3..9caddbf556 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/fetch/@tanstack/vue-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/fetch/@tanstack/vue-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; +import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, skipToken, type UseMutationOptions } from '@tanstack/vue-query'; import { client } from '../client.gen'; import { apiVVersionODataControllerCount, callToTestOrderOfParams, callWithDefaultOptionalParameters, callWithDefaultParameters, callWithDescriptions, callWithDuplicateResponses, callWithNoContentResponse, callWithParameters, callWithResponse, callWithResponseAndNoContentResponse, callWithResponses, callWithResultFromHeader, callWithWeirdParameterNames, collectionFormat, complexParams, complexTypes, deleteCallWithoutParametersAndResponse, deleteFoo, deprecatedCall, dummyA, dummyB, duplicateName, duplicateName2, duplicateName3, duplicateName4, export_, fileResponse, fooWow, getApiVbyApiVersionSimpleOperation, getCallWithOptionalParam, getCallWithoutParametersAndResponse, import_, multipartRequest, multipartResponse, nonAsciiæøåÆøÅöôêÊ字符串, type Options, patchApiVbyApiVersionNoTag, patchCallWithoutParametersAndResponse, postApiVbyApiVersionFormData, postApiVbyApiVersionRequestBody, postCallWithOptionalParam, postCallWithoutParametersAndResponse, putCallWithoutParametersAndResponse, putWithFormUrlEncoded, testErrorCode, types, uploadFile } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const exportQueryKey = (options?: Options) => createQueryKey('export', options); -export const exportOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const exportOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await export_({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const exportOptions = (options?: Options) => queryOptions>): UseMutationOptions> => { @@ -98,8 +102,8 @@ export const fooWowMutation = (options?: Partial>): UseMutat export const apiVVersionODataControllerCountQueryKey = (options?: Options) => createQueryKey('apiVVersionODataControllerCount', options); -export const apiVVersionODataControllerCountOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const apiVVersionODataControllerCountOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await apiVVersionODataControllerCount({ ...options, ...queryKey[0], @@ -107,14 +111,14 @@ export const apiVVersionODataControllerCountOptions = (options?: Options) => createQueryKey('getApiVbyApiVersionSimpleOperation', options); -export const getApiVbyApiVersionSimpleOperationOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getApiVbyApiVersionSimpleOperationOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getApiVbyApiVersionSimpleOperation({ ...options, ...queryKey[0], @@ -122,8 +126,8 @@ export const getApiVbyApiVersionSimpleOperationOptions = (options: Options>): UseMutationOptions> => { @@ -142,8 +146,8 @@ export const deleteCallWithoutParametersAndResponseMutation = (options?: Partial export const getCallWithoutParametersAndResponseQueryKey = (options?: Options) => createQueryKey('getCallWithoutParametersAndResponse', options); -export const getCallWithoutParametersAndResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithoutParametersAndResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithoutParametersAndResponse({ ...options, ...queryKey[0], @@ -151,8 +155,8 @@ export const getCallWithoutParametersAndResponseOptions = (options?: Options>): UseMutationOptions> => { @@ -272,8 +276,8 @@ export const callWithWeirdParameterNamesMutation = (options?: Partial) => createQueryKey('getCallWithOptionalParam', options); -export const getCallWithOptionalParamOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getCallWithOptionalParamOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getCallWithOptionalParam({ ...options, ...queryKey[0], @@ -281,8 +285,8 @@ export const getCallWithOptionalParamOptions = (options: Options[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey, page: K) => { @@ -316,10 +320,10 @@ const createInfiniteParams = [0], 'body' | 'hea export const getCallWithOptionalParamInfiniteQueryKey = (options: Options): QueryKey> => createQueryKey('getCallWithOptionalParam', options, true); -export const getCallWithOptionalParamInfiniteOptions = (options: Options) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( +export const getCallWithOptionalParamInfiniteOptions = (options: Options | typeof skipToken) => infiniteQueryOptions, QueryKey>, number | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { - queryFn: async ({ pageParam, queryKey, signal }) => { + queryFn: resolveQueryFn(options, async ({ pageParam, queryKey, signal }) => { // @ts-ignore const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { query: { @@ -334,8 +338,8 @@ export const getCallWithOptionalParamInfiniteOptions = (options: Options>): UseMutationOptions> => { @@ -382,8 +386,8 @@ export const postApiVbyApiVersionFormDataMutation = (options?: Partial) => createQueryKey('callWithDefaultParameters', options); -export const callWithDefaultParametersOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithDefaultParametersOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithDefaultParameters({ ...options, ...queryKey[0], @@ -391,8 +395,8 @@ export const callWithDefaultParametersOptions = (options?: Options>): UseMutationOptions> => { @@ -439,8 +443,8 @@ export const duplicateNameMutation = (options?: Partial) => createQueryKey('duplicateName2', options); -export const duplicateName2Options = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const duplicateName2Options = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await duplicateName2({ ...options, ...queryKey[0], @@ -448,8 +452,8 @@ export const duplicateName2Options = (options?: Options) => throwOnError: true }); return data; - }, - queryKey: duplicateName2QueryKey(options) + }), + queryKey: duplicateName2QueryKey(resolveOptions(options)) }); export const duplicateName3Mutation = (options?: Partial>): UseMutationOptions> => { @@ -482,8 +486,8 @@ export const duplicateName4Mutation = (options?: Partial) => createQueryKey('callWithNoContentResponse', options); -export const callWithNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithNoContentResponse({ ...options, ...queryKey[0], @@ -491,14 +495,14 @@ export const callWithNoContentResponseOptions = (options?: Options) => createQueryKey('callWithResponseAndNoContentResponse', options); -export const callWithResponseAndNoContentResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseAndNoContentResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponseAndNoContentResponse({ ...options, ...queryKey[0], @@ -506,14 +510,14 @@ export const callWithResponseAndNoContentResponseOptions = (options?: Options) => createQueryKey('dummyA', options); -export const dummyAOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyAOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyA({ ...options, ...queryKey[0], @@ -521,14 +525,14 @@ export const dummyAOptions = (options?: Options) => queryOptions) => createQueryKey('dummyB', options); -export const dummyBOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const dummyBOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await dummyB({ ...options, ...queryKey[0], @@ -536,14 +540,14 @@ export const dummyBOptions = (options?: Options) => queryOptions) => createQueryKey('callWithResponse', options); -export const callWithResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const callWithResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await callWithResponse({ ...options, ...queryKey[0], @@ -551,8 +555,8 @@ export const callWithResponseOptions = (options?: Options) throwOnError: true }); return data; - }, - queryKey: callWithResponseQueryKey(options) + }), + queryKey: callWithResponseQueryKey(resolveOptions(options)) }); export const callWithDuplicateResponsesMutation = (options?: Partial>): UseMutationOptions> => { @@ -585,8 +589,8 @@ export const callWithResponsesMutation = (options?: Partial) => createQueryKey('collectionFormat', options); -export const collectionFormatOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const collectionFormatOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await collectionFormat({ ...options, ...queryKey[0], @@ -594,14 +598,14 @@ export const collectionFormatOptions = (options: Options) throwOnError: true }); return data; - }, - queryKey: collectionFormatQueryKey(options) + }), + queryKey: collectionFormatQueryKey(resolveOptions(options)) }); export const typesQueryKey = (options: Options) => createQueryKey('types', options); -export const typesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const typesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await types({ ...options, ...queryKey[0], @@ -609,8 +613,8 @@ export const typesOptions = (options: Options) => queryOptions>): UseMutationOptions> => { @@ -629,8 +633,8 @@ export const uploadFileMutation = (options?: Partial>): export const fileResponseQueryKey = (options: Options) => createQueryKey('fileResponse', options); -export const fileResponseOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const fileResponseOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await fileResponse({ ...options, ...queryKey[0], @@ -638,14 +642,14 @@ export const fileResponseOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: fileResponseQueryKey(options) + }), + queryKey: fileResponseQueryKey(resolveOptions(options)) }); export const complexTypesQueryKey = (options: Options) => createQueryKey('complexTypes', options); -export const complexTypesOptions = (options: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const complexTypesOptions = (options: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await complexTypes({ ...options, ...queryKey[0], @@ -653,14 +657,14 @@ export const complexTypesOptions = (options: Options) => query throwOnError: true }); return data; - }, - queryKey: complexTypesQueryKey(options) + }), + queryKey: complexTypesQueryKey(resolveOptions(options)) }); export const multipartResponseQueryKey = (options?: Options) => createQueryKey('multipartResponse', options); -export const multipartResponseOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const multipartResponseOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await multipartResponse({ ...options, ...queryKey[0], @@ -668,8 +672,8 @@ export const multipartResponseOptions = (options?: Options>): UseMutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/name-builder/@tanstack/vue-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/name-builder/@tanstack/vue-query.gen.ts index bfd35f1d62..3c3f7038e9 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/name-builder/@tanstack/vue-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/plugins/@tanstack/vue-query/name-builder/@tanstack/vue-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/vue-query'; +import { type DefaultError, queryOptions, skipToken, type UseMutationOptions } from '@tanstack/vue-query'; import { client } from '../client.gen'; import { fooBarPost, fooBarPut, fooPost, fooPut, getFoo, getFooBar, type Options } from '../sdk.gen'; @@ -39,10 +39,14 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const getFooD = (options?: Options) => createQueryKey('getFoo', options); -export const getFooE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFoo({ ...options, ...queryKey[0], @@ -50,8 +54,8 @@ export const getFooE = (options?: Options) => queryOptions>): UseMutationOptions> => { @@ -84,8 +88,8 @@ export const fooPutC = (options?: Partial>): UseMutationOpti export const getFooBarD = (options?: Options) => createQueryKey('getFooBar', options); -export const getFooBarE = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const getFooBarE = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await getFooBar({ ...options, ...queryKey[0], @@ -93,8 +97,8 @@ export const getFooBarE = (options?: Options) => queryOptions>): UseMutationOptions> => { diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-tanstack-react-query/@tanstack/react-query.gen.ts b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-tanstack-react-query/@tanstack/react-query.gen.ts index 197e707f4c..19423c5c77 100644 --- a/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-tanstack-react-query/@tanstack/react-query.gen.ts +++ b/packages/openapi-ts-tests/main/test/__snapshots__/3.1.x/sse-tanstack-react-query/@tanstack/react-query.gen.ts @@ -1,6 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type DefaultError, queryOptions } from '@tanstack/react-query'; +import { type DefaultError, queryOptions, skipToken, useQuery } from '@tanstack/react-query'; import { client } from '../client.gen'; import { listEvents, type Options } from '../sdk.gen'; @@ -39,13 +39,17 @@ const createQueryKey = (id: string, options?: TOptions return [params]; }; +const resolveOptions = (options: T | typeof skipToken) => options === skipToken ? undefined : options; + +const resolveQueryFn = (options: T | typeof skipToken, queryFn: T) => options === skipToken ? skipToken : queryFn; + export const listEventsQueryKey = (options?: Options) => createQueryKey('listEvents', options); /** * List events */ -export const listEventsOptions = (options?: Options) => queryOptions>({ - queryFn: async ({ queryKey, signal }) => { +export const listEventsOptions = (options?: Options | typeof skipToken) => queryOptions>({ + queryFn: resolveQueryFn(options, async ({ queryKey, signal }) => { const { data } = await listEvents({ ...options, ...queryKey[0], @@ -53,6 +57,21 @@ export const listEventsOptions = (options?: Options) => queryOpt throwOnError: true }); return data; - }, - queryKey: listEventsQueryKey(options) + }), + queryKey: listEventsQueryKey(resolveOptions(options)) }); + +const queryWithOptions = (optionsFn: (...args: Array) => any, options?: any) => { + if (typeof options !== 'object' && options !== undefined) { + return useQuery(optionsFn(options)); + } + const { queryOptions, ...sdkOptions } = options ?? {}; + return useQuery({ ...optionsFn(sdkOptions), ...queryOptions }); +}; + +/** + * List events + */ +export const useListEventsQuery = (options?: (Options | typeof skipToken) & { + queryOptions?: Partial, 'queryKey' | 'queryFn'>>; +}) => queryWithOptions(listEventsOptions, options); diff --git a/packages/openapi-ts-tests/main/test/plugins.test.ts b/packages/openapi-ts-tests/main/test/plugins.test.ts index 426e15a52e..37666cbacf 100644 --- a/packages/openapi-ts-tests/main/test/plugins.test.ts +++ b/packages/openapi-ts-tests/main/test/plugins.test.ts @@ -64,6 +64,20 @@ for (const version of versions) { }), description: 'generate Fetch API client with TanStack React Query plugin', }, + { + config: createConfig({ + output: 'useQuery-disabled', + plugins: [ + { + name: '@tanstack/react-query', + useQuery: false, + }, + '@hey-api/client-fetch', + ], + }), + description: + 'generate Fetch API client with TanStack React Query plugin with useQuery disabled', + }, { config: createConfig({ output: 'fetch', diff --git a/packages/openapi-ts/src/plugins/@tanstack/preact-query/config.ts b/packages/openapi-ts/src/plugins/@tanstack/preact-query/config.ts index d72a8963aa..7d10468427 100644 --- a/packages/openapi-ts/src/plugins/@tanstack/preact-query/config.ts +++ b/packages/openapi-ts/src/plugins/@tanstack/preact-query/config.ts @@ -85,7 +85,7 @@ export const defaultConfig: TanStackPreactQueryPlugin['Config'] = { plugin.config.useQuery = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', - enabled: false, + enabled: true, name: 'use{{name}}Query', }, mappers: { diff --git a/packages/openapi-ts/src/plugins/@tanstack/preact-query/types.ts b/packages/openapi-ts/src/plugins/@tanstack/preact-query/types.ts index bf48ffb24a..60d54149d6 100644 --- a/packages/openapi-ts/src/plugins/@tanstack/preact-query/types.ts +++ b/packages/openapi-ts/src/plugins/@tanstack/preact-query/types.ts @@ -339,7 +339,7 @@ export type UserConfig = Plugin.Name<'@tanstack/preact-query'> & * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * - * @default false + * @default true */ useQuery?: | boolean diff --git a/packages/openapi-ts/src/plugins/@tanstack/query-core/queryKey.ts b/packages/openapi-ts/src/plugins/@tanstack/query-core/queryKey.ts index 319df26e56..ab0996213d 100644 --- a/packages/openapi-ts/src/plugins/@tanstack/query-core/queryKey.ts +++ b/packages/openapi-ts/src/plugins/@tanstack/query-core/queryKey.ts @@ -160,6 +160,57 @@ export const createQueryKeyType = ({ plugin }: { plugin: PluginInstance }) => { plugin.node(queryKeyType); }; +export const createSkipTokenHelpers = ({ plugin }: { plugin: PluginInstance }) => { + const symbolSkipToken = $(plugin.external(`${plugin.name}.skipToken`)); + + const symbolResolveOptions = plugin.symbol( + applyNaming('resolveOptions', { case: plugin.config.case }), + { + meta: { + category: 'utility', + resource: 'resolveOptions', + tool: plugin.name, + }, + }, + ); + plugin.node( + $.const(symbolResolveOptions).assign( + $.func() + .generic('T') + .param('options', (p) => p.type($.type.or('T', $.type.query(symbolSkipToken)))) + .do( + $.return( + $.ternary($('options').eq(symbolSkipToken)).do($('undefined')).otherwise($('options')), + ), + ), + ), + ); + + const symbolResolveQueryFn = plugin.symbol( + applyNaming('resolveQueryFn', { case: plugin.config.case }), + { + meta: { + category: 'utility', + resource: 'resolveQueryFn', + tool: plugin.name, + }, + }, + ); + plugin.node( + $.const(symbolResolveQueryFn).assign( + $.func() + .generic('T') + .param('options', (p) => p.type($.type.or('T', $.type.query(symbolSkipToken)))) + .param('queryFn', (p) => p.type('T')) + .do( + $.return( + $.ternary($('options').eq(symbolSkipToken)).do(symbolSkipToken).otherwise($('queryFn')), + ), + ), + ), + ); +}; + export const queryKeyStatement = ({ isInfinite, operation, diff --git a/packages/openapi-ts/src/plugins/@tanstack/query-core/v5/infiniteQueryOptions.ts b/packages/openapi-ts/src/plugins/@tanstack/query-core/v5/infiniteQueryOptions.ts index 4b124afa23..9e7fe59b86 100644 --- a/packages/openapi-ts/src/plugins/@tanstack/query-core/v5/infiniteQueryOptions.ts +++ b/packages/openapi-ts/src/plugins/@tanstack/query-core/v5/infiniteQueryOptions.ts @@ -7,7 +7,12 @@ import { } from '../../../../plugins/shared/utils/operation'; import type { TsDsl } from '../../../../ts-dsl'; import { $ } from '../../../../ts-dsl'; -import { createQueryKeyFunction, createQueryKeyType, queryKeyStatement } from '../queryKey'; +import { + createQueryKeyFunction, + createQueryKeyType, + createSkipTokenHelpers, + queryKeyStatement, +} from '../queryKey'; import { handleMeta } from '../shared/meta'; import { useTypeData, useTypeError, useTypeResponse } from '../shared/useType'; import type { PluginInstance } from '../types'; @@ -123,6 +128,16 @@ export const createInfiniteQueryOptions = ({ createQueryKeyFunction({ plugin }); } + if ( + !plugin.getSymbol({ + category: 'utility', + resource: 'resolveOptions', + tool: plugin.name, + }) + ) { + createSkipTokenHelpers({ plugin }); + } + if ( !plugin.getSymbol({ category: 'utility', @@ -139,6 +154,19 @@ export const createInfiniteQueryOptions = ({ const typeData = useTypeData({ operation, plugin }); const typeResponse = useTypeResponse({ operation, plugin }); + const symbolSkipToken = $(plugin.external(`${plugin.name}.skipToken`)); + + const symbolResolveOptions = plugin.referenceSymbol({ + category: 'utility', + resource: 'resolveOptions', + tool: plugin.name, + }); + const symbolResolveQueryFn = plugin.referenceSymbol({ + category: 'utility', + resource: 'resolveQueryFn', + tool: plugin.name, + }); + const symbolQueryKeyType = plugin.referenceSymbol({ category: 'type', resource: 'QueryKey', @@ -216,6 +244,13 @@ export const createInfiniteQueryOptions = ({ statements.push($.const().object('data').assign(awaitSdkFn), $.return('data')); } + const asyncQueryFn = $.func() + .async() + .param((p) => p.object('pageParam', 'queryKey', 'signal')) + .do(...statements); + + const paramType = $.type.or(typeData, $.type.query(symbolSkipToken)); + const symbolInfiniteQueryOptionsFn = plugin.symbol( applyNaming(operation.id, plugin.config.infiniteQueryOptions), ); @@ -224,7 +259,7 @@ export const createInfiniteQueryOptions = ({ .$if(plugin.config.comments && createOperationComment(operation), (c, v) => c.doc(v)) .assign( $.func() - .param('options', (p) => p.required(isRequiredOptions).type(typeData)) + .param('options', (p) => p.required(isRequiredOptions).type(paramType)) .do( $.return( $(symbolInfiniteQueryOptions) @@ -232,14 +267,11 @@ export const createInfiniteQueryOptions = ({ $.object() .pretty() .hint('@ts-ignore') + .prop('queryFn', $(symbolResolveQueryFn).call($('options'), asyncQueryFn)) .prop( - 'queryFn', - $.func() - .async() - .param((p) => p.object('pageParam', 'queryKey', 'signal')) - .do(...statements), + 'queryKey', + $(symbolInfiniteQueryKey).call($(symbolResolveOptions).call($('options'))), ) - .prop('queryKey', $(symbolInfiniteQueryKey).call('options')) .$if(handleMeta(plugin, operation, 'infiniteQueryOptions'), (o, v) => o.prop('meta', v), ), diff --git a/packages/openapi-ts/src/plugins/@tanstack/query-core/v5/plugin.ts b/packages/openapi-ts/src/plugins/@tanstack/query-core/v5/plugin.ts index aba629cebf..fade412785 100644 --- a/packages/openapi-ts/src/plugins/@tanstack/query-core/v5/plugin.ts +++ b/packages/openapi-ts/src/plugins/@tanstack/query-core/v5/plugin.ts @@ -1,10 +1,22 @@ -import type { PluginHandler } from '../types'; +import type { PluginHandler, PluginInstance } from '../types'; import { createInfiniteQueryOptions } from './infiniteQueryOptions'; import { createMutationOptions } from './mutationOptions'; import { createQueryOptions } from './queryOptions'; import { createUseMutation } from './useMutation'; import { createUseQuery } from './useQuery'; +const createQueryStyleNames = new Set([ + '@tanstack/angular-query-experimental', + '@tanstack/solid-query', + '@tanstack/svelte-query', +]); + +const getMutationOptionsType = (name: PluginInstance['name']) => + createQueryStyleNames.has(name) ? 'MutationOptions' : 'UseMutationOptions'; + +const getQueryOptionsType = (name: PluginInstance['name']) => + createQueryStyleNames.has(name) ? 'CreateQueryOptions' : 'UseQueryOptions'; + export const handlerV5: PluginHandler = ({ plugin }) => { plugin.symbol('DefaultError', { external: plugin.name, @@ -22,13 +34,7 @@ export const handlerV5: PluginHandler = ({ plugin }) => { resource: `${plugin.name}.InfiniteData`, }, }); - const mutationsType = - plugin.name === '@tanstack/angular-query-experimental' || - plugin.name === '@tanstack/svelte-query' || - plugin.name === '@tanstack/solid-query' - ? 'MutationOptions' - : 'UseMutationOptions'; - plugin.symbol(mutationsType, { + plugin.symbol(getMutationOptionsType(plugin.name), { external: plugin.name, kind: 'type', meta: { @@ -64,6 +70,22 @@ export const handlerV5: PluginHandler = ({ plugin }) => { resource: `${plugin.name}.useQuery`, }, }); + plugin.symbol(getQueryOptionsType(plugin.name), { + external: plugin.name, + kind: 'type', + meta: { + category: 'external', + resource: `${plugin.name}.QueryObserverOptions`, + }, + }); + plugin.symbol('skipToken', { + external: plugin.name, + meta: { + category: 'external', + resource: `${plugin.name}.skipToken`, + }, + }); + plugin.symbol('AxiosError', { external: 'axios', kind: 'type', diff --git a/packages/openapi-ts/src/plugins/@tanstack/query-core/v5/queryOptions.ts b/packages/openapi-ts/src/plugins/@tanstack/query-core/v5/queryOptions.ts index 01fc9ac80e..5322d6492e 100644 --- a/packages/openapi-ts/src/plugins/@tanstack/query-core/v5/queryOptions.ts +++ b/packages/openapi-ts/src/plugins/@tanstack/query-core/v5/queryOptions.ts @@ -8,7 +8,12 @@ import { } from '../../../../plugins/shared/utils/operation'; import type { TsDsl } from '../../../../ts-dsl'; import { $ } from '../../../../ts-dsl'; -import { createQueryKeyFunction, createQueryKeyType, queryKeyStatement } from '../queryKey'; +import { + createQueryKeyFunction, + createQueryKeyType, + createSkipTokenHelpers, + queryKeyStatement, +} from '../queryKey'; import { handleMeta } from '../shared/meta'; import { useTypeData, useTypeError, useTypeResponse } from '../shared/useType'; import type { PluginInstance } from '../types'; @@ -42,6 +47,16 @@ export const createQueryOptions = ({ createQueryKeyFunction({ plugin }); } + if ( + !plugin.getSymbol({ + category: 'utility', + resource: 'resolveOptions', + tool: plugin.name, + }) + ) { + createSkipTokenHelpers({ plugin }); + } + const symbolQueryOptions = plugin.external(`${plugin.name}.queryOptions`); const symbolQueryKey = plugin.symbol(applyNaming(operation.id, plugin.config.queryKeys)); @@ -55,6 +70,19 @@ export const createQueryOptions = ({ const typeResponse = useTypeResponse({ operation, plugin }); + const symbolSkipToken = $(plugin.external(`${plugin.name}.skipToken`)); + + const symbolResolveOptions = plugin.referenceSymbol({ + category: 'utility', + resource: 'resolveOptions', + tool: plugin.name, + }); + const symbolResolveQueryFn = plugin.referenceSymbol({ + category: 'utility', + resource: 'resolveQueryFn', + tool: plugin.name, + }); + const awaitSdkFn = $.lazy((ctx) => ctx .access( @@ -81,18 +109,20 @@ export const createQueryOptions = ({ statements.push($.const().object('data').assign(awaitSdkFn), $.return('data')); } + const asyncQueryFn = $.func() + .async() + .param((p) => p.object('queryKey', 'signal')) + .do(...statements); + const queryOptionsObj = $.object() .pretty() - .prop( - 'queryFn', - $.func() - .async() - .param((p) => p.object('queryKey', 'signal')) - .do(...statements), - ) - .prop('queryKey', $(symbolQueryKey).call(optionsParamName)) + .prop('queryFn', $(symbolResolveQueryFn).call($(optionsParamName), asyncQueryFn)) + .prop('queryKey', $(symbolQueryKey).call($(symbolResolveOptions).call($(optionsParamName)))) .$if(handleMeta(plugin, operation, 'queryOptions'), (o, v) => o.prop('meta', v)); + const typeData = useTypeData({ operation, plugin }); + const paramType = $.type.or(typeData, $.type.query(symbolSkipToken)); + const symbolQueryOptionsFn = plugin.symbol( applyNaming(operation.id, plugin.config.queryOptions), { @@ -112,9 +142,7 @@ export const createQueryOptions = ({ .$if(plugin.config.comments && createOperationComment(operation), (c, v) => c.doc(v)) .assign( $.func() - .param(optionsParamName, (p) => - p.required(isRequiredOptions).type(useTypeData({ operation, plugin })), - ) + .param(optionsParamName, (p) => p.required(isRequiredOptions).type(paramType)) .do( $(symbolQueryOptions) .call(queryOptionsObj) diff --git a/packages/openapi-ts/src/plugins/@tanstack/query-core/v5/useQuery.ts b/packages/openapi-ts/src/plugins/@tanstack/query-core/v5/useQuery.ts index 76b359ffda..e8a679eb29 100644 --- a/packages/openapi-ts/src/plugins/@tanstack/query-core/v5/useQuery.ts +++ b/packages/openapi-ts/src/plugins/@tanstack/query-core/v5/useQuery.ts @@ -11,6 +11,45 @@ import { useTypeData } from '../shared/useType'; import type { PluginInstance } from '../types'; const optionsParamName = 'options'; +const queryOptionsKey = 'queryOptions'; +const sdkOptionsName = 'sdkOptions'; +const helperName = 'queryWithOptions'; + +export const createQueryWithOptionsHelper = ({ plugin }: { plugin: PluginInstance }): void => { + const symbolUseQuery = plugin.external(`${plugin.name}.useQuery`); + + const symbolHelper = plugin.symbol( + applyNaming(helperName, { + case: plugin.config.case, + }), + { + meta: { + category: 'utility', + resource: helperName, + tool: plugin.name, + }, + }, + ); + + const fn = $.const(symbolHelper).assign( + $.func() + .param('optionsFn', (p) => p.type('(...args: Array) => any')) + .param(optionsParamName, (p) => p.optional().type('any')) + .do( + $.if($(`typeof ${optionsParamName} !== 'object' && ${optionsParamName} !== undefined`)).do( + $(symbolUseQuery).call($('optionsFn').call(optionsParamName)).return(), + ), + $.const() + .object(queryOptionsKey) + .spread(sdkOptionsName) + .assign($(optionsParamName).coalesce($.object())), + $(symbolUseQuery) + .call($.object().spread($('optionsFn').call(sdkOptionsName)).spread(queryOptionsKey)) + .return(), + ), + ); + plugin.node(fn); +}; export const createUseQuery = ({ operation, @@ -27,9 +66,23 @@ export const createUseQuery = ({ return; } - const symbolUseQueryFn = plugin.symbol(applyNaming(operation.id, plugin.config.useQuery)); + if ( + !plugin.getSymbol({ + category: 'utility', + resource: helperName, + tool: plugin.name, + }) + ) { + createQueryWithOptionsHelper({ plugin }); + } - const symbolUseQuery = plugin.external(`${plugin.name}.useQuery`); + const symbolHelper = plugin.referenceSymbol({ + category: 'utility', + resource: helperName, + tool: plugin.name, + }); + + const symbolUseQueryFn = plugin.symbol(applyNaming(operation.id, plugin.config.useQuery)); const isRequiredOptions = isOperationOptionsRequired({ context: plugin.context, @@ -37,6 +90,9 @@ export const createUseQuery = ({ }); const typeData = useTypeData({ operation, plugin }); + const symbolSkipToken = $(plugin.external(`${plugin.name}.skipToken`)); + const sdkParamType = $.type.or(typeData, $.type.query(symbolSkipToken)); + const symbolQueryOptionsFn = plugin.referenceSymbol({ category: 'hook', resource: 'operation', @@ -44,13 +100,28 @@ export const createUseQuery = ({ role: 'queryOptions', tool: plugin.name, }); + + const queryOptionsType = $.type('Partial').generic( + $.type('Omit', (t) => + t.generics( + $(symbolQueryOptionsFn).returnType(), + $.type.or($.type.literal('queryKey'), $.type.literal('queryFn')), + ), + ), + ); + + const mergedParamType = $.type.and( + sdkParamType, + $.type.object().prop(queryOptionsKey, (p) => p.optional().type(queryOptionsType)), + ); + const statement = $.const(symbolUseQueryFn) .export() .$if(plugin.config.comments && createOperationComment(operation), (c, v) => c.doc(v)) .assign( $.func() - .param(optionsParamName, (p) => p.required(isRequiredOptions).type(typeData)) - .do($(symbolUseQuery).call($(symbolQueryOptionsFn).call(optionsParamName)).return()), + .param(optionsParamName, (p) => p.required(isRequiredOptions).type(mergedParamType)) + .do($(symbolHelper).call(symbolQueryOptionsFn, optionsParamName).return()), ); plugin.node(statement); }; diff --git a/packages/openapi-ts/src/plugins/@tanstack/react-query/config.ts b/packages/openapi-ts/src/plugins/@tanstack/react-query/config.ts index 41ee1f1fa4..17afd0bdf7 100644 --- a/packages/openapi-ts/src/plugins/@tanstack/react-query/config.ts +++ b/packages/openapi-ts/src/plugins/@tanstack/react-query/config.ts @@ -85,7 +85,7 @@ export const defaultConfig: TanStackReactQueryPlugin['Config'] = { plugin.config.useQuery = context.valueToObject({ defaultValue: { case: plugin.config.case ?? 'camelCase', - enabled: false, + enabled: true, name: 'use{{name}}Query', }, mappers: { diff --git a/packages/openapi-ts/src/plugins/@tanstack/react-query/types.ts b/packages/openapi-ts/src/plugins/@tanstack/react-query/types.ts index 7022351dc2..97d3959b19 100644 --- a/packages/openapi-ts/src/plugins/@tanstack/react-query/types.ts +++ b/packages/openapi-ts/src/plugins/@tanstack/react-query/types.ts @@ -339,7 +339,7 @@ export type UserConfig = Plugin.Name<'@tanstack/react-query'> & * - `string` or `function`: Shorthand for `{ name: string | function }` * - `object`: Full configuration object * - * @default false + * @default true */ useQuery?: | boolean