7
7
type UseSuspenseQueryResult ,
8
8
useMutation ,
9
9
useQuery ,
10
+ useSuspenseQuery ,
10
11
} from "@tanstack/react-query" ;
11
12
import type { ClientMethod , FetchResponse , MaybeOptionalInit , Client as FetchClient } from "openapi-fetch" ;
12
13
import type { HasRequiredKeys , HttpMethod , MediaType , PathsWithMethod } from "openapi-typescript-helpers" ;
@@ -53,10 +54,12 @@ export type UseMutationMethod<Paths extends Record<string, Record<HttpMethod, {}
53
54
54
55
export interface OpenapiQueryClient < Paths extends { } , Media extends MediaType = MediaType > {
55
56
useQuery : UseQueryMethod < Paths , Media > ;
56
- useSuspenseQery : any ;
57
+ useSuspenseQuery : UseSuspenseQueryMethod < Paths , Media > ;
57
58
useMutation : UseMutationMethod < Paths , Media > ;
58
59
}
59
60
61
+ // TODO: Move the client[method]() fn outside for reusability
62
+ // TODO: Add the ability to bring queryClient as argument
60
63
export default function createClient < Paths extends { } , Media extends MediaType = MediaType > (
61
64
client : FetchClient < Paths , Media > ,
62
65
) : OpenapiQueryClient < Paths , Media > {
@@ -76,11 +79,25 @@ export default function createClient<Paths extends {}, Media extends MediaType =
76
79
...options ,
77
80
} ) ;
78
81
} ,
79
- useSuspenseQery : ( ) => { } ,
82
+ useSuspenseQuery : ( method , path , ...[ init , options ] ) => {
83
+ return useSuspenseQuery ( {
84
+ queryKey : [ method , path , init ] ,
85
+ queryFn : async ( ) => {
86
+ const mth = method . toUpperCase ( ) as keyof typeof client ;
87
+ const fn = client [ mth ] as ClientMethod < Paths , typeof method , Media > ;
88
+ const { data, error } = await fn ( path , init as any ) ; // TODO: find a way to avoid as any
89
+ if ( error || ! data ) {
90
+ throw error ;
91
+ }
92
+ return data ;
93
+ } ,
94
+ } ) ;
95
+ } ,
80
96
useMutation : ( method , path , options ) => {
81
97
return useMutation ( {
82
98
mutationKey : [ method , path ] ,
83
99
mutationFn : async ( init ) => {
100
+ // TODO: Put in external fn for reusability
84
101
const mth = method . toUpperCase ( ) as keyof typeof client ;
85
102
const fn = client [ mth ] as ClientMethod < Paths , typeof method , Media > ;
86
103
const { data, error } = await fn ( path , init as any ) ; // TODO: find a way to avoid as any
0 commit comments