|
| 1 | +import type { |
| 2 | + SeamHttpApiError, |
| 3 | + SeamHttpEndpointsWithoutWorkspace, |
| 4 | + SeamHttpEndpointWithoutWorkspaceQueryPaths, |
| 5 | +} from '@seamapi/http/connect' |
| 6 | +import { |
| 7 | + useQuery, |
| 8 | + type UseQueryOptions, |
| 9 | + type UseQueryResult, |
| 10 | +} from '@tanstack/react-query' |
| 11 | + |
| 12 | +import { useSeamClient } from 'lib/seam/use-seam-client.js' |
| 13 | + |
| 14 | +export type UseSeamQueryWithoutWorkspaceParameters< |
| 15 | + T extends SeamHttpEndpointWithoutWorkspaceQueryPaths, |
| 16 | +> = Parameters<SeamHttpEndpointsWithoutWorkspace[T]>[0] |
| 17 | + |
| 18 | +export type UseSeamQueryWithoutWorkspaceResult< |
| 19 | + T extends SeamHttpEndpointWithoutWorkspaceQueryPaths, |
| 20 | +> = UseQueryResult<QueryData<T>, SeamHttpApiError> |
| 21 | + |
| 22 | +export function useSeamQueryWithoutWorkspace< |
| 23 | + T extends SeamHttpEndpointWithoutWorkspaceQueryPaths, |
| 24 | +>( |
| 25 | + endpointPath: T, |
| 26 | + parameters?: UseSeamQueryWithoutWorkspaceParameters<T>, |
| 27 | + options: Parameters<SeamHttpEndpointsWithoutWorkspace[T]>[1] & |
| 28 | + QueryOptions<QueryData<T>, SeamHttpApiError> = {} |
| 29 | +): UseSeamQueryWithoutWorkspaceResult<T> { |
| 30 | + const { endpointClient: client, queryKeyPrefixes } = useSeamClient() |
| 31 | + return useQuery({ |
| 32 | + enabled: client != null, |
| 33 | + ...options, |
| 34 | + queryKey: [ |
| 35 | + ...queryKeyPrefixes, |
| 36 | + ...endpointPath.split('/').filter((v) => v !== ''), |
| 37 | + parameters, |
| 38 | + ], |
| 39 | + queryFn: async () => { |
| 40 | + if (client == null) return null |
| 41 | + // Using @ts-expect-error over any is preferred, but not possible here because TypeScript will run out of memory. |
| 42 | + // Type assertion is needed here for performance reasons. The types are correct at runtime. |
| 43 | + const endpoint = client[endpointPath] as (...args: any) => Promise<any> |
| 44 | + return await endpoint(parameters, options) |
| 45 | + }, |
| 46 | + }) |
| 47 | +} |
| 48 | + |
| 49 | +type QueryData<T extends SeamHttpEndpointWithoutWorkspaceQueryPaths> = Awaited< |
| 50 | + ReturnType<SeamHttpEndpointsWithoutWorkspace[T]> |
| 51 | +> |
| 52 | + |
| 53 | +type QueryOptions<X, Y> = Omit<UseQueryOptions<X, Y>, 'queryKey' | 'queryFn'> |
0 commit comments