Skip to content

Commit 65d7f09

Browse files
authored
Add custom fetch option (openapi-ts#1119)
1 parent 13233c2 commit 65d7f09

File tree

5 files changed

+29
-4
lines changed

5 files changed

+29
-4
lines changed

CHANGELOG.md

+6
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
# openapi-fetch
22

3+
## 0.2.0
4+
5+
### Minor Changes
6+
7+
- 97c8757: Add custom fetch option (#51). Thanks, [@hd-o](https://github.com/hd-o)!
8+
39
## 0.1.4
410

511
### Patch Changes

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,7 @@ createClient<paths>(options);
144144
| Name | Type | Description |
145145
| :-------------- | :------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
146146
| `baseUrl` | `string` | Prefix all fetch URLs with this option (e.g. `"https://myapi.dev/v1/"`). |
147+
| `fetch` | `fetch` | Fetch function used for requests (defaults to `globalThis.fetch`) |
147148
| (Fetch options) | | Any valid fetch option (`headers`, `mode`, `cache`, `signal` …) (<a href="https://developer.mozilla.org/en-US/docs/Web/API/fetch#options" target="_blank" rel="noopener noreferrer">docs</a>) |
148149

149150
### Fetch options

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252
"openapi-typescript": "workspace:^",
5353
"prettier": "^2.8.8",
5454
"typescript": "^5.0.4",
55-
"vitest": "^0.31.0",
55+
"vitest": "^0.31.1",
5656
"vitest-fetch-mock": "^0.2.2"
5757
}
5858
}

src/index.test.ts

+14
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,20 @@ describe("client", () => {
180180
})
181181
);
182182
});
183+
184+
it("accepts a custom fetch function", async () => {
185+
const data = { works: true };
186+
const client = createClient<paths>({
187+
fetch: async () =>
188+
Promise.resolve({
189+
headers: new Headers(),
190+
json: async () => data,
191+
status: 200,
192+
ok: true,
193+
} as Response),
194+
});
195+
expect((await client.get("/self", {})).data).toBe(data);
196+
});
183197
});
184198

185199
describe("get()", () => {

src/index.ts

+7-3
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ const DEFAULT_HEADERS = {
77
interface ClientOptions extends RequestInit {
88
/** set the common root URL for all API requests */
99
baseUrl?: string;
10+
/** custom fetch (defaults to globalThis.fetch) */
11+
fetch?: typeof fetch;
1012
}
1113
export interface BaseParams {
1214
params?: { query?: Record<string, unknown> };
@@ -51,17 +53,19 @@ export type FetchResponse<T> =
5153
| { data: T extends { responses: any } ? NonNullable<FilterKeys<Success<T["responses"]>, JSONLike>> : unknown; error?: never; response: Response }
5254
| { data?: never; error: T extends { responses: any } ? NonNullable<FilterKeys<Error<T["responses"]>, JSONLike>> : unknown; response: Response };
5355

54-
export default function createClient<Paths extends {}>(options?: ClientOptions) {
56+
export default function createClient<Paths extends {}>(clientOptions: ClientOptions = {}) {
57+
const { fetch = globalThis.fetch, ...options } = clientOptions;
58+
5559
const defaultHeaders = new Headers({
5660
...DEFAULT_HEADERS,
57-
...(options?.headers ?? {}),
61+
...(options.headers ?? {}),
5862
});
5963

6064
async function coreFetch<P extends keyof Paths, M extends HttpMethod>(url: P, fetchOptions: FetchOptions<M extends keyof Paths[P] ? Paths[P][M] : never>): Promise<FetchResponse<M extends keyof Paths[P] ? Paths[P][M] : unknown>> {
6165
const { headers, body: requestBody, params = {}, querySerializer = (q: QuerySerializer<M extends keyof Paths[P] ? Paths[P][M] : never>) => new URLSearchParams(q as any).toString(), ...init } = fetchOptions || {};
6266

6367
// URL
64-
let finalURL = `${options?.baseUrl ?? ""}${url as string}`;
68+
let finalURL = `${options.baseUrl ?? ""}${url as string}`;
6569
if ((params as any).path) {
6670
for (const [k, v] of Object.entries((params as any).path)) finalURL = finalURL.replace(`{${k}}`, encodeURIComponent(String(v)));
6771
}

0 commit comments

Comments
 (0)