Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions packages/openapi-react-query/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
type DataTag,
type InfiniteData,
type QueryClient,
type QueryFunctionContext,
Expand Down Expand Up @@ -65,8 +66,9 @@ export type QueryOptionsFunction<Paths extends Record<string, Record<HttpMethod,
InferSelectReturnType<Response["data"], Options["select"]>,
QueryKey<Paths, Method, Path>
>,
"queryFn"
"queryFn" | "queryKey"
> & {
queryKey: DataTag<QueryKey<Paths, Method, Path>, Response["data"], Response["error"]>;
queryFn: Exclude<
UseQueryOptions<
Response["data"],
Expand Down Expand Up @@ -209,10 +211,10 @@ export default function createClient<Paths extends {}, Media extends MediaType =
};

const queryOptions: QueryOptionsFunction<Paths, Media> = (method, path, ...[init, options]) => ({
queryKey: (init === undefined ? ([method, path] as const) : ([method, path, init] as const)) as QueryKey<
Paths,
typeof method,
typeof path
queryKey: (init === undefined ? ([method, path] as const) : ([method, path, init] as const)) as DataTag<
QueryKey<Paths, typeof method, typeof path>,
any,
any
>,
queryFn,
...options,
Expand Down
43 changes: 43 additions & 0 deletions packages/openapi-react-query/test/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,49 @@ describe("client", () => {
client.queryOptions("get", "/blogposts/{post_id}", {});
});

it("correctly infers return type from query key", async () => {
const fetchClient = createFetchClient<paths>({ baseUrl });
const client = createClient(fetchClient);

const initialData = { title: "Initial data", body: "Initial data" };

const options = client.queryOptions(
"get",
"/blogposts/{post_id}",
{
params: {
path: {
post_id: "1",
},
},
},
{
initialData: () => initialData,
},
);

const data = queryClient.getQueryData(options.queryKey);

expectTypeOf(data).toEqualTypeOf<
| {
title: string;
body: string;
publish_date?: number;
}
| undefined
>();
expect(data).toEqual(undefined);

const { result } = renderHook(() => useQuery({ ...options, enabled: false, select: (data) => data }), {
wrapper,
});

await waitFor(() => expect(result.current.isFetching).toBe(false));

expect(result.current.data).toEqual(initialData);
expect(result.current.error).toBeNull();
});

it("returns query options that can resolve data correctly with fetchQuery", async () => {
const response = { title: "title", body: "body" };
const fetchClient = createFetchClient<paths>({ baseUrl });
Expand Down