Skip to content

Commit 1954028

Browse files
committed
custom fetch per call
1 parent ea65d72 commit 1954028

File tree

2 files changed

+24
-14
lines changed

2 files changed

+24
-14
lines changed

packages/openapi-fetch/src/index.test.ts

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -396,18 +396,26 @@ describe("client", () => {
396396
});
397397

398398
it("accepts a custom fetch function", async () => {
399-
const data = { works: true };
400-
const customFetch = {
401-
clone: () => ({ ...customFetch }),
402-
headers: new Headers(),
403-
json: async () => data,
404-
status: 200,
405-
ok: true,
406-
};
407-
const client = createClient<paths>({
408-
fetch: async () => Promise.resolve(customFetch as Response),
409-
});
410-
expect((await client.GET("/self")).data).toBe(data);
399+
function createCustomFetch(data: any) {
400+
const response = {
401+
clone: () => ({ ...response }),
402+
headers: new Headers(),
403+
json: async () => data,
404+
status: 200,
405+
ok: true,
406+
} as Response;
407+
return async () => Promise.resolve(response);
408+
}
409+
410+
const baseData = { works: true };
411+
const customBaseFetch = createCustomFetch(baseData);
412+
const client = createClient<paths>({ fetch: customBaseFetch });
413+
expect((await client.GET("/self")).data).toBe(baseData);
414+
415+
const data = { result: "it's working" };
416+
const customFetch = createCustomFetch(data);
417+
const customResponse = await client.GET("/self", { fetch: customFetch });
418+
expect(customResponse.data).toBe(data);
411419
});
412420
});
413421

packages/openapi-fetch/src/index.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,8 @@ export type RequestBodyOption<T> = OperationRequestBodyContent<T> extends never
7070
? { body?: OperationRequestBodyContent<T> }
7171
: { body: OperationRequestBodyContent<T> };
7272

73-
export type FetchOptions<T> = RequestOptions<T> & Omit<RequestInit, "body">;
73+
export type FetchOptions<T> = RequestOptions<T> &
74+
Omit<RequestInit, "body"> & { fetch?: ClientOptions["fetch"] };
7475

7576
export type FetchResponse<T> =
7677
| {
@@ -95,7 +96,7 @@ export default function createClient<Paths extends {}>(
9596
clientOptions: ClientOptions = {},
9697
) {
9798
const {
98-
fetch = globalThis.fetch,
99+
fetch: baseFetch = globalThis.fetch,
99100
querySerializer: globalQuerySerializer,
100101
bodySerializer: globalBodySerializer,
101102
...options
@@ -110,6 +111,7 @@ export default function createClient<Paths extends {}>(
110111
fetchOptions: FetchOptions<M extends keyof Paths[P] ? Paths[P][M] : never>,
111112
): Promise<FetchResponse<M extends keyof Paths[P] ? Paths[P][M] : unknown>> {
112113
const {
114+
fetch = baseFetch,
113115
headers,
114116
body: requestBody,
115117
params = {},

0 commit comments

Comments
 (0)