Skip to content

Fix openapi fetch types #1378

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 8, 2023
Merged
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
4 changes: 4 additions & 0 deletions packages/openapi-fetch/.npmignore
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
.eslintignore
.prettierignore
examples
test
vitest.config.ts
2 changes: 1 addition & 1 deletion packages/openapi-fetch/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@
"del-cli": "^5.1.0",
"esbuild": "^0.19.4",
"nanostores": "^0.9.3",
"openapi-typescript": "workspace:^",
"openapi-typescript": "^6.7.0",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Locks openapi-typescript to v6 temporarily

"openapi-typescript-codegen": "^0.25.0",
"openapi-typescript-fetch": "^1.1.3",
"superagent": "^8.1.2",
Expand Down
15 changes: 5 additions & 10 deletions packages/openapi-fetch/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,27 +51,21 @@ export interface DefaultParamsOption {
params?: { query?: Record<string, unknown> };
}

export interface EmptyParameters {
query?: never;
header?: never;
path?: never;
cookie?: never;
}

export type ParamsOption<T> = T extends { parameters: any }
? HasRequiredKeys<T["parameters"]> extends never
? { params?: T["parameters"] }
: { params: T["parameters"] }
: never;
: DefaultParamsOption;
// v7 breaking change: TODO uncomment for openapi-typescript@7 support
// : never;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a minor breaking change: in openapi-typescript@7, more structures are generated as never, including all parameters, so the inference is improved. But in v6, missing items are simply omitted. This is the only place that makes a difference, but it’s still a breaking change nonetheless and it means openapi-fetch will need a breaking release when the time comes.


export type RequestBodyOption<T> = OperationRequestBodyContent<T> extends never
? { body?: never }
: undefined extends OperationRequestBodyContent<T>
? { body?: OperationRequestBodyContent<T> }
: { body: OperationRequestBodyContent<T> };

export type FetchOptions<T> = RequestOptions<T> &
Omit<RequestInit, "body"> & { fetch?: ClientOptions["fetch"] };
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn’t change the option itself; just moved to be with the other options (it was inconsistent here)

export type FetchOptions<T> = RequestOptions<T> & Omit<RequestInit, "body">;

export type FetchResponse<T> =
| {
Expand All @@ -90,6 +84,7 @@ export type RequestOptions<T> = ParamsOption<T> &
querySerializer?: QuerySerializer<T>;
bodySerializer?: BodySerializer<T>;
parseAs?: ParseAs;
fetch?: ClientOptions["fetch"];
};

export default function createClient<Paths extends {}>(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { atom, computed } from "nanostores";
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
// @ts-expect-error
import createFetchMock from "vitest-fetch-mock";
import type { paths } from "../test/v1.js";
import createClient from "./index.js";
import createClient from "../src/index.js";
import type { paths } from "./v1.d.js";

const fetchMocker = createFetchMock(vi);

Expand Down Expand Up @@ -395,7 +395,7 @@ describe("client", () => {
expect(options?.headers).toEqual(new Headers());
});

it("accepts a custom fetch function", async () => {
it("accepts a custom fetch function on createClient", async () => {
function createCustomFetch(data: any) {
const response = {
clone: () => ({ ...response }),
Expand All @@ -407,15 +407,48 @@ describe("client", () => {
return async () => Promise.resolve(response);
}

const baseData = { works: true };
const customBaseFetch = createCustomFetch(baseData);
const client = createClient<paths>({ fetch: customBaseFetch });
expect((await client.GET("/self")).data).toBe(baseData);
const customFetch = createCustomFetch({ works: true });
mockFetchOnce({ status: 200, body: "{}" });

const client = createClient<paths>({ fetch: customFetch });
const { data } = await client.GET("/self");

// assert data was returned from custom fetcher
expect(data).toEqual({ works: true });

// assert global fetch was never called
expect(fetchMocker).not.toHaveBeenCalled();
});

it("accepts a custom fetch function per-request", async () => {
function createCustomFetch(data: any) {
const response = {
clone: () => ({ ...response }),
headers: new Headers(),
json: async () => data,
status: 200,
ok: true,
} as Response;
return async () => Promise.resolve(response);
}

const fallbackFetch = createCustomFetch({ fetcher: "fallback" });
const overrideFetch = createCustomFetch({ fetcher: "override" });

mockFetchOnce({ status: 200, body: "{}" });

const client = createClient<paths>({ fetch: fallbackFetch });

// assert override function was called
const fetch1 = await client.GET("/self", { fetch: overrideFetch });
expect(fetch1.data).toEqual({ fetcher: "override" });

// assert fallback function still persisted (and wasn’t overridden)
const fetch2 = await client.GET("/self");
expect(fetch2.data).toEqual({ fetcher: "fallback" });

const data = { result: "it's working" };
const customFetch = createCustomFetch(data);
const customResponse = await client.GET("/self", { fetch: customFetch });
expect(customResponse.data).toBe(data);
// assert global fetch was never called
expect(fetchMocker).not.toHaveBeenCalled();
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was an important part missing from the original test—testing that global fetch wasn’t actually invoked (we could assume, based on the data, but we weren’t explicitly checking).

});
});

Expand Down
Loading