Skip to content
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

[feat]: parseAs options reports correct data type #1428

Merged
merged 10 commits into from
Dec 6, 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
213 changes: 74 additions & 139 deletions packages/openapi-fetch/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,19 @@ export type QuerySerializer<T> = (

export type BodySerializer<T> = (body: OperationRequestBodyContent<T>) => any;

export type ParseAs = "json" | "text" | "blob" | "arrayBuffer" | "stream";
type BodyType<T = unknown> = {
json: T;
text: Awaited<ReturnType<Response["text"]>>;
blob: Awaited<ReturnType<Response["blob"]>>;
arrayBuffer: Awaited<ReturnType<Response["arrayBuffer"]>>;
stream: Response["body"];
};
export type ParseAs = keyof BodyType;
export type ParseAsResponse<T, O extends FetchOptions> = O extends {
parseAs: ParseAs;
}
? BodyType<T>[O["parseAs"]]
: T;

export interface DefaultParamsOption {
params?: {
Expand All @@ -62,9 +74,20 @@ export type RequestBodyOption<T> = OperationRequestBodyContent<T> extends never

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

export type FetchResponse<T> =
/** This type helper makes the 2nd function param required if params/requestBody are required; otherwise, optional */
export type MaybeOptionalInit<
P extends {},
M extends keyof P,
> = HasRequiredKeys<FetchOptions<FilterKeys<P, M>>> extends never
? [(FetchOptions<FilterKeys<P, M>> | undefined)?]
: [FetchOptions<FilterKeys<P, M>>];

export type FetchResponse<T, O extends FetchOptions> =
| {
data: FilterKeys<SuccessResponse<ResponseObjectMap<T>>, MediaType>;
data: ParseAsResponse<
FilterKeys<SuccessResponse<ResponseObjectMap<T>>, MediaType>,
O
>;
error?: never;
response: Response;
}
Expand All @@ -86,157 +109,69 @@ export default function createClient<Paths extends {}>(
clientOptions?: ClientOptions,
): {
/** Call a GET endpoint */
GET<P extends PathsWithMethod<Paths, "get">>(
GET<
P extends PathsWithMethod<Paths, "get">,
I extends MaybeOptionalInit<Paths[P], "get">,
>(
url: P,
...init: HasRequiredKeys<
FetchOptions<FilterKeys<Paths[P], "get">>
> extends never
? [(FetchOptions<FilterKeys<Paths[P], "get">> | undefined)?]
: [FetchOptions<FilterKeys<Paths[P], "get">>]
): Promise<
FetchResponse<
"get" extends infer T
? T extends "get"
? T extends keyof Paths[P]
? Paths[P][T]
: unknown
: never
: never
>
>;
...init: I
): Promise<FetchResponse<Paths[P]["get"], I[0]>>;
/** Call a PUT endpoint */
PUT<P extends PathsWithMethod<Paths, "put">>(
PUT<
P extends PathsWithMethod<Paths, "put">,
I extends MaybeOptionalInit<Paths[P], "put">,
>(
url: P,
...init: HasRequiredKeys<
FetchOptions<FilterKeys<Paths[P], "put">>
> extends never
? [(FetchOptions<FilterKeys<Paths[P], "put">> | undefined)?]
: [FetchOptions<FilterKeys<Paths[P], "put">>]
): Promise<
FetchResponse<
"put" extends infer T
? T extends "put"
? T extends keyof Paths[P]
? Paths[P][T]
: unknown
: never
: never
>
>;
...init: I
): Promise<FetchResponse<Paths[P]["put"], I[0]>>;
/** Call a POST endpoint */
POST<P extends PathsWithMethod<Paths, "post">>(
POST<
P extends PathsWithMethod<Paths, "post">,
I extends MaybeOptionalInit<Paths[P], "post">,
>(
url: P,
...init: HasRequiredKeys<
FetchOptions<FilterKeys<Paths[P], "post">>
> extends never
? [(FetchOptions<FilterKeys<Paths[P], "post">> | undefined)?]
: [FetchOptions<FilterKeys<Paths[P], "post">>]
): Promise<
FetchResponse<
"post" extends infer T
? T extends "post"
? T extends keyof Paths[P]
? Paths[P][T]
: unknown
: never
: never
>
>;
...init: I
): Promise<FetchResponse<Paths[P]["post"], I[0]>>;
/** Call a DELETE endpoint */
DELETE<P extends PathsWithMethod<Paths, "delete">>(
DELETE<
P extends PathsWithMethod<Paths, "delete">,
I extends MaybeOptionalInit<Paths[P], "delete">,
>(
url: P,
...init: HasRequiredKeys<
FetchOptions<FilterKeys<Paths[P], "delete">>
> extends never
? [(FetchOptions<FilterKeys<Paths[P], "delete">> | undefined)?]
: [FetchOptions<FilterKeys<Paths[P], "delete">>]
): Promise<
FetchResponse<
"delete" extends infer T
? T extends "delete"
? T extends keyof Paths[P]
? Paths[P][T]
: unknown
: never
: never
>
>;
...init: I
): Promise<FetchResponse<Paths[P]["delete"], I[0]>>;
/** Call a OPTIONS endpoint */
OPTIONS<P extends PathsWithMethod<Paths, "options">>(
OPTIONS<
P extends PathsWithMethod<Paths, "options">,
I extends MaybeOptionalInit<Paths[P], "options">,
>(
url: P,
...init: HasRequiredKeys<
FetchOptions<FilterKeys<Paths[P], "options">>
> extends never
? [(FetchOptions<FilterKeys<Paths[P], "options">> | undefined)?]
: [FetchOptions<FilterKeys<Paths[P], "options">>]
): Promise<
FetchResponse<
"options" extends infer T
? T extends "options"
? T extends keyof Paths[P]
? Paths[P][T]
: unknown
: never
: never
>
>;
...init: I
): Promise<FetchResponse<Paths[P]["options"], I[0]>>;
/** Call a HEAD endpoint */
HEAD<P extends PathsWithMethod<Paths, "head">>(
HEAD<
P extends PathsWithMethod<Paths, "head">,
I extends MaybeOptionalInit<Paths[P], "head">,
>(
url: P,
...init: HasRequiredKeys<
FetchOptions<FilterKeys<Paths[P], "head">>
> extends never
? [(FetchOptions<FilterKeys<Paths[P], "head">> | undefined)?]
: [FetchOptions<FilterKeys<Paths[P], "head">>]
): Promise<
FetchResponse<
"head" extends infer T
? T extends "head"
? T extends keyof Paths[P]
? Paths[P][T]
: unknown
: never
: never
>
>;
...init: I
): Promise<FetchResponse<Paths[P]["head"], I[0]>>;
/** Call a PATCH endpoint */
PATCH<P extends PathsWithMethod<Paths, "patch">>(
PATCH<
P extends PathsWithMethod<Paths, "patch">,
I extends MaybeOptionalInit<Paths[P], "patch">,
>(
url: P,
...init: HasRequiredKeys<
FetchOptions<FilterKeys<Paths[P], "patch">>
> extends never
? [(FetchOptions<FilterKeys<Paths[P], "patch">> | undefined)?]
: [FetchOptions<FilterKeys<Paths[P], "patch">>]
): Promise<
FetchResponse<
"patch" extends infer T
? T extends "patch"
? T extends keyof Paths[P]
? Paths[P][T]
: unknown
: never
: never
>
>;
...init: I
): Promise<FetchResponse<Paths[P]["patch"], I[0]>>;
/** Call a TRACE endpoint */
TRACE<P extends PathsWithMethod<Paths, "trace">>(
TRACE<
P extends PathsWithMethod<Paths, "trace">,
I extends MaybeOptionalInit<Paths[P], "trace">,
>(
url: P,
...init: HasRequiredKeys<
FetchOptions<FilterKeys<Paths[P], "trace">>
> extends never
? [(FetchOptions<FilterKeys<Paths[P], "trace">> | undefined)?]
: [FetchOptions<FilterKeys<Paths[P], "trace">>]
): Promise<
FetchResponse<
"trace" extends infer T
? T extends "trace"
? T extends keyof Paths[P]
? Paths[P][T]
: unknown
: never
: never
>
>;
...init: I
): Promise<FetchResponse<Paths[P]["trace"], I[0]>>;
};

/** Serialize query params to string */
Expand Down
5 changes: 3 additions & 2 deletions packages/openapi-fetch/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ export default function createClient(clientOptions) {

/**
* Per-request fetch (keeps settings created in createClient()
* @param {string} url
* @param {import('./index.js').FetchOptions} fetchOptions
* @param {T} url
* @param {import('./index.js').FetchOptions<T>} fetchOptions
*/
async function coreFetch(url, fetchOptions) {
const {
Expand Down Expand Up @@ -50,6 +50,7 @@ export default function createClient(clientOptions) {
);

// fetch!
/** @type {RequestInit} */
const requestInit = {
redirect: "follow",
...baseOptions,
Expand Down
42 changes: 33 additions & 9 deletions packages/openapi-fetch/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -569,32 +569,56 @@ describe("client", () => {
it("text", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
const { data } = await client.GET("/anyMethod", { parseAs: "text" });
expect(data).toBe("{}");
const { data, error } = (await client.GET("/anyMethod", {
parseAs: "text",
})) satisfies { data?: string };
if (error) {
throw new Error(`parseAs text: error`);
}
expect(data.toLowerCase()).toBe("{}");
});

it("arrayBuffer", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
const { data } = await client.GET("/anyMethod", {
const { data, error } = (await client.GET("/anyMethod", {
parseAs: "arrayBuffer",
});
expect(data instanceof ArrayBuffer).toBe(true);
})) satisfies { data?: ArrayBuffer };
if (error) {
throw new Error(`parseAs arrayBuffer: error`);
}
expect(data.byteLength).toBe(2);
});

it("blob", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
const { data } = await client.GET("/anyMethod", { parseAs: "blob" });
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((data as any).constructor.name).toBe("Blob");
const { data, error } = (await client.GET("/anyMethod", {
parseAs: "blob",
})) satisfies { data?: Blob };
if (error) {
throw new Error(`parseAs blob: error`);
}

expect(data.constructor.name).toBe("Blob");
});

it("stream", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
const { data } = await client.GET("/anyMethod", { parseAs: "stream" });
const { data } = (await client.GET("/anyMethod", {
parseAs: "stream",
})) satisfies { data?: ReadableStream<Uint8Array> | null };
if (!data) {
throw new Error(`parseAs stream: error`);
}

expect(data instanceof Buffer).toBe(true);
if (!(data instanceof Buffer)) {
throw Error("Data should be an instance of Buffer in Node context");
}

expect(data.byteLength).toBe(2);
});
});
});
Expand Down
22 changes: 16 additions & 6 deletions packages/openapi-fetch/test/v7-beta.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -578,31 +578,41 @@ describe("client", () => {
it("text", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
const { data } = await client.GET("/anyMethod", { parseAs: "text" });
const { data }: { data?: string } = await client.GET("/anyMethod", {
parseAs: "text",
});
expect(data).toBe("{}");
});

it("arrayBuffer", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
const { data } = await client.GET("/anyMethod", {
parseAs: "arrayBuffer",
});
const { data }: { data?: ArrayBuffer } = await client.GET(
"/anyMethod",
{
parseAs: "arrayBuffer",
},
);
expect(data instanceof ArrayBuffer).toBe(true);
});

it("blob", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
const { data } = await client.GET("/anyMethod", { parseAs: "blob" });
const { data }: { data?: Blob } = await client.GET("/anyMethod", {
parseAs: "blob",
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((data as any).constructor.name).toBe("Blob");
});

it("stream", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
const { data } = await client.GET("/anyMethod", { parseAs: "stream" });
const { data }: { data?: ReadableStream | null } = await client.GET(
"/anyMethod",
{ parseAs: "stream" },
);
expect(data instanceof Buffer).toBe(true);
});
});
Expand Down
4 changes: 1 addition & 3 deletions packages/openapi-typescript-helpers/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,7 @@ export type ErrorResponse<T> = FilterKeys<
// Generic TS utils

/** Find first match of multiple keys */
export type FilterKeys<Obj, Matchers> = {
[K in keyof Obj]: K extends Matchers ? Obj[K] : never;
}[keyof Obj];
export type FilterKeys<Obj, Matchers> = Obj[keyof Obj & Matchers];
/** Return any `[string]/[string]` media type (important because openapi-fetch allows any content response, not just JSON-like) */
export type MediaType = `${string}/${string}`;
/** Filter objects that have required keys */
Expand Down