Skip to content

Commit 09c2ee5

Browse files
committed
add MethodResponse for openapi-react-query
1 parent c65795a commit 09c2ee5

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

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

+12-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import {
1111
useQuery,
1212
useSuspenseQuery,
1313
} from "@tanstack/react-query";
14-
import type { ClientMethod, FetchResponse, MaybeOptionalInit, Client as FetchClient } from "openapi-fetch";
14+
import type { ClientMethod, FetchResponse, MaybeOptionalInit, Client as FetchClient, ClientPathsWithMethod } from "openapi-fetch";
1515
import type { HttpMethod, MediaType, PathsWithMethod, RequiredKeysOf } from "openapi-typescript-helpers";
1616

1717
type InitWithUnknowns<Init> = Init & { [key: string]: unknown };
@@ -93,6 +93,16 @@ export interface OpenapiQueryClient<Paths extends {}, Media extends MediaType =
9393
useMutation: UseMutationMethod<Paths, Media>;
9494
}
9595

96+
export type MethodResponse<
97+
CreatedClient extends OpenapiQueryClient<any, any>,
98+
Method extends HttpMethod,
99+
Path extends ClientPathsWithMethod<FetchClient<any, any>, Method>,
100+
Options = {}
101+
> =
102+
CreatedClient extends OpenapiQueryClient<infer Paths extends { [key: string]: any }, infer Media extends MediaType>
103+
? NonNullable<FetchResponse<Paths[Path][Method], Options, Media>["data"]>
104+
: never
105+
96106
// TODO: Add the ability to bring queryClient as argument
97107
export default function createClient<Paths extends {}, Media extends MediaType = MediaType>(
98108
client: FetchClient<Paths, Media>,
@@ -141,3 +151,4 @@ export default function createClient<Paths extends {}, Media extends MediaType =
141151
),
142152
};
143153
}
154+

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

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { afterAll, beforeAll, describe, expect, it } from "vitest";
22
import { server, baseUrl, useMockRequestHandler } from "./fixtures/mock-server.js";
33
import type { paths } from "./fixtures/api.js";
4-
import createClient from "../src/index.js";
4+
import createClient, { type MethodResponse } from "../src/index.js";
55
import createFetchClient from "openapi-fetch";
66
import { fireEvent, render, renderHook, screen, waitFor, act } from "@testing-library/react";
77
import { QueryClient, QueryClientProvider, useQueries } from "@tanstack/react-query";
@@ -212,6 +212,7 @@ describe("client", () => {
212212

213213
const { data, error } = result.current;
214214

215+
expectTypeOf(data).toEqualTypeOf<MethodResponse<typeof client, "get", "/string-array"> | undefined>();
215216
expectTypeOf(data).toEqualTypeOf<string[] | undefined>();
216217
expectTypeOf(error).toEqualTypeOf<{ code: number; message: string } | null>();
217218
});

0 commit comments

Comments
 (0)