Skip to content

Commit c09116b

Browse files
committed
feat: if throw true data is returned as it's
1 parent 3fa1cdd commit c09116b

File tree

3 files changed

+26
-8
lines changed

3 files changed

+26
-8
lines changed

src/fetch.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -127,9 +127,7 @@ export const betterFetch = async <
127127
}
128128

129129
if (options?.throw) {
130-
return {
131-
data: successContext.data,
132-
} as any;
130+
return successContext.data as any;
133131
}
134132

135133
return {

src/test/fetch.test.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,3 +224,27 @@ describe("fetch-error", () => {
224224
await expect(f("/ok")).rejects.toThrowError(BetterFetchError);
225225
});
226226
});
227+
228+
describe("fetch-error-throw", () => {
229+
const f = createFetch({
230+
baseURL: "http://localhost:4001",
231+
customFetchImpl: async (req, init) => {
232+
const url = new URL(req.toString());
233+
if (url.pathname.startsWith("/ok")) {
234+
return new Response(JSON.stringify({ message: "ok" }));
235+
}
236+
return new Response(null, {
237+
status: 500,
238+
});
239+
},
240+
throw: true,
241+
});
242+
it("should throw if the response is not ok", async () => {
243+
await expect(f("/not-ok")).rejects.toThrowError(BetterFetchError);
244+
});
245+
246+
it("should return data without error object", async () => {
247+
const res = await f<{ message: "ok" }>("/ok");
248+
expect(res).toEqual({ message: "ok" });
249+
});
250+
});

src/types.ts

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -149,8 +149,4 @@ export type BetterFetchResponse<
149149
T,
150150
E extends Record<string, unknown> | unknown = unknown,
151151
Throw extends boolean = false,
152-
> = Throw extends true
153-
? {
154-
data: T;
155-
}
156-
: Data<T> | Error<E>;
152+
> = Throw extends true ? T : Data<T> | Error<E>;

0 commit comments

Comments
 (0)