Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using custom fetch auto generates SecondParameter type with any #1838

Open
oferitz opened this issue Jan 21, 2025 · 0 comments
Open

Using custom fetch auto generates SecondParameter type with any #1838

oferitz opened this issue Jan 21, 2025 · 0 comments
Labels
tanstack-query TanStack Query related issue

Comments

@oferitz
Copy link

oferitz commented Jan 21, 2025

Description

When using a custom fetch implementation with Orval, the generated client files produce types with any that trigger Biome linter warnings. This issue doesn't occur when using Orval's built-in fetch.

Configuration

Current Orval configuration:

output: {
  baseUrl: '/api',
  target: 'src/generated/client',
  schemas: 'src/generated/schemas',
  client: 'react-query',
  httpClient: 'fetch',
  mode: 'tags',
  mock: false,
  clean: true,
  biome: true,
  override: {
    fetch: {
      includeHttpResponseReturnType: false
    },
    mutator: {
      path: 'src/custom-fetch.ts',
      name: 'customFetch'
    }
  }
}

Problem

The generated client uses the following type definition:

type SecondParameter<T extends (...args: any) => any> = Parameters<T>[1]

This results in complex type definitions in the generated hooks:

export function useFoo
  TData = Awaited<ReturnType<typeof getFoo>>,
  TError =
    | E400Response
    | E401Response
    | E403Response
    | E404Response
    | E409Response
    | E422Response
    | E429Response
    | E500Response
>(options: {
  query: Partial
    UseQueryOptions
      Awaited<ReturnType<typeof getFoo>>,
      TError,
      TData
    >
  > &
    Pick
      DefinedInitialDataOptions
        Awaited<ReturnType<typeof getFoo>>,
        TError,
        TData
      >,
      'initialData'
    >
  request?: SecondParameter<typeof customFetch>
}): DefinedUseQueryResult<TData, TError> & {
  queryKey: DataTag<QueryKey, TData>
}

Current Implementation

For reference, here's my custom fetch implementation:

const getBody = async <T>(response: Response): Promise<T> => {
  const contentType = response.headers.get('content-type')

  if (contentType?.includes('application/json')) {
    return response.json()
  }

  if (contentType?.includes('application/pdf')) {
    return response.blob() as Promise<T>
  }

  return response.text() as Promise<T>
}

const getUrl = (contextUrl: string): string => {
  const baseUrl = process.env.NEXT_PUBLIC_API_BASE_URL
  const url = new URL(`${baseUrl}${contextUrl}`)
  const pathname = url.pathname
  const search = url.search
  const requestUrl = new URL(`${baseUrl}${pathname}${search}`)
  return requestUrl.toString()
}

const getHeaders = async (headers?: HeadersInit): Promise<HeadersInit> => {
  // Add more headers here if needed
  return {
    ...headers,
  }
}

const handleErrorResponse = async (response: Response): Promise<never> => {
  // Handle errors nicely here
}

// Type definition for the request function
type CustomFetchFunction = <T>(url: string, init?: RequestInit) => Promise<T>

// The actual implementation with explicit typing
export const customFetch: CustomFetchFunction = async <T>(
  url: string,
  init?: RequestInit
): Promise<T> => {
  const requestUrl = getUrl(url)
  const requestHeaders = await getHeaders(init?.headers)

  const response = await fetch(requestUrl, {
    ...init,
    headers: requestHeaders,
  })

  // Handle 204 No Content
  if (response.status === 204) {
    return {} as T
  }

  // Handle error responses
  if (!response.ok) {
    await handleErrorResponse(response)
  }

  const data = await getBody<T>(response)
  return data
}

Questions

  1. How can I eliminate the any type in my custom fetch implementation?
  2. Why doesn't this issue occur with Orval's built-in fetch?

Any insights or solutions would be greatly appreciated.

@melloware melloware added the fetch Fetch client related issue label Jan 21, 2025
@soartec-lab soartec-lab added tanstack-query TanStack Query related issue and removed fetch Fetch client related issue labels Feb 1, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
tanstack-query TanStack Query related issue
Projects
None yet
Development

No branches or pull requests

3 participants