Skip to content

Commit 314ae91

Browse files
committed
Drop init argument when not needed in query key
For urls that do not include an init param, generate a query key of length 2. This allows the value to be passed directly to `invalidateQueries()`. Without this change, the package generates `["get", "/foo", undefined]` which does not correctly match the corresponding get query. Related to openapi-ts#1806
1 parent 5dc47e0 commit 314ae91

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

packages/openapi-react-query/src/index.ts

+3-2
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@ export type QueryKey<
2121
Paths extends Record<string, Record<HttpMethod, {}>>,
2222
Method extends HttpMethod,
2323
Path extends PathsWithMethod<Paths, Method>,
24-
> = readonly [Method, Path, MaybeOptionalInit<Paths[Path], Method>];
24+
Init = MaybeOptionalInit<Paths[Path], Method>,
25+
> = Init extends undefined ? readonly [Method, Path] : readonly [Method, Path, Init];
2526

2627
export type QueryOptionsFunction<Paths extends Record<string, Record<HttpMethod, {}>>, Media extends MediaType> = <
2728
Method extends HttpMethod,
@@ -123,7 +124,7 @@ export default function createClient<Paths extends {}, Media extends MediaType =
123124
};
124125

125126
const queryOptions: QueryOptionsFunction<Paths, Media> = (method, path, ...[init, options]) => ({
126-
queryKey: [method, path, init as InitWithUnknowns<typeof init>] as const,
127+
queryKey: (init === undefined ? [method, path] as const : [method, path, init] as const) as QueryKey<Paths, typeof method, typeof path>,
127128
queryFn,
128129
...options,
129130
});

packages/openapi-react-query/test/index.test.tsx

+10
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,16 @@ describe("client", () => {
231231
expectTypeOf(result.current.data).toEqualTypeOf<"select(true)">();
232232
expectTypeOf(result.current.error).toEqualTypeOf<false | null>();
233233
});
234+
235+
it("returns query options without an init", async () => {
236+
const fetchClient = createFetchClient<minimalGetPaths>({
237+
baseUrl,
238+
fetch: () => Promise.resolve(Response.json(true)),
239+
});
240+
const client = createClient(fetchClient);
241+
242+
expect(client.queryOptions("get", "/foo").queryKey.length).toBe(2);
243+
});
234244
});
235245

236246
describe("useQuery", () => {

0 commit comments

Comments
 (0)