Skip to content

Commit 0fd02d6

Browse files
better-release[bot]bytaesu
authored andcommitted
fix(client): correct return types when throw option is true (#148)
1 parent db51636 commit 0fd02d6

2 files changed

Lines changed: 41 additions & 6 deletions

File tree

packages/better-call/src/client.test.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,4 +328,29 @@ describe("client", () => {
328328
client("@post/test");
329329
client("/test2");
330330
});
331+
332+
it("should return unwrapped type T when throw: true is set", async () => {
333+
const itemEndpoint = createEndpoint(
334+
"/item",
335+
{ method: "GET" },
336+
async () => ({ id: "123", name: "test" }),
337+
);
338+
339+
const router = createRouter({ itemEndpoint });
340+
341+
const client = createClient<typeof router>({
342+
baseURL: "http://localhost:3000",
343+
customFetchImpl: async (url, init) => {
344+
return router.handler(new Request(url, init));
345+
},
346+
});
347+
348+
const res = await client("/item", {
349+
throw: true,
350+
});
351+
352+
expect(res).toMatchObject({ id: "123", name: "test" });
353+
354+
expectTypeOf(res).toExtend<{ id: string; name: string }>();
355+
});
331356
});

packages/better-call/src/client.ts

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,11 @@ export type RequiredOptionKeys<
8585
params: true;
8686
});
8787

88-
export const createClient = <R extends Router | Router["endpoints"]>(
89-
options?: ClientOptions,
88+
export const createClient = <
89+
R extends Router | Router["endpoints"],
90+
GlobalOpts extends ClientOptions = ClientOptions,
91+
>(
92+
options?: GlobalOpts,
9093
) => {
9194
const fetch = createFetch(options ?? {});
9295
type API = InferClientRoutes<
@@ -109,23 +112,30 @@ export const createClient = <R extends Router | Router["endpoints"]>(
109112
OPT extends O,
110113
K extends keyof OPT,
111114
C extends InferContext<OPT[K]>,
115+
CallOpts extends BetterFetchOption<C["body"], C["query"], C["params"]>,
112116
>(
113117
path: K,
114-
...options: HasRequired<C> extends true
118+
...callOptions: HasRequired<C> extends true
115119
? [
116120
WithRequired<
117121
BetterFetchOption<C["body"], C["query"], C["params"]>,
118122
keyof RequiredOptionKeys<C>
119123
>,
120124
]
121-
: [BetterFetchOption<C["body"], C["query"], C["params"]>?]
125+
: [CallOpts?]
122126
): Promise<
123127
BetterFetchResponse<
124-
Awaited<ReturnType<OPT[K] extends Endpoint ? OPT[K] : never>>
128+
Awaited<ReturnType<OPT[K] extends Endpoint ? OPT[K] : never>>,
129+
unknown,
130+
CallOpts["throw"] extends boolean
131+
? CallOpts["throw"]
132+
: GlobalOpts["throw"] extends true
133+
? true
134+
: false
125135
>
126136
> => {
127137
return (await fetch(path as string, {
128-
...options[0],
138+
...callOptions[0],
129139
})) as any;
130140
};
131141
};

0 commit comments

Comments
 (0)