Skip to content

Commit 8e4f287

Browse files
committed
feat: preserve form data objects in request body
1 parent ccdecd8 commit 8e4f287

File tree

3 files changed

+20
-6
lines changed

3 files changed

+20
-6
lines changed

src/openapi-typescript/fetch-factory.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -62,12 +62,13 @@ function buildInit(
6262
options: AllFetchOptions,
6363
headers: HeadersInit
6464
): RequestInit {
65+
const serializableObject =
66+
options.body &&
67+
typeof options.body == "object" &&
68+
!((options.body as any) instanceof FormData);
6569
return {
6670
...Object.assign({}, { ...defaultInit }, { ...options }),
67-
body:
68-
options.body && typeof options.body == "object"
69-
? JSON.stringify(options.body)
70-
: options.body,
71+
body: serializableObject ? JSON.stringify(options.body) : options.body,
7172
method: options.method?.toUpperCase(),
7273
headers,
7374
};

src/openapi-typescript/types/fetch-options.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ export type FetchOptions<Operation> = Omit<
2323
*/
2424
export type AllFetchOptions<Operation = never> = Omit<RequestInit, "body"> & {
2525
parameters: FetchParameters<Operation>;
26-
body: OperationRequestBody<Operation> | string;
26+
body: OperationRequestBody<Operation> | string | FormData;
2727
};
2828

2929
/**

test/openapi-typescript/fetch-factory.test.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,7 @@ describe("Generated fetch request", () => {
265265
expect((mockedFetch.mock.calls[0] as any)[1].integrity).toBe("dummy");
266266
});
267267

268-
it("stringifies request body", () => {
268+
it("stringifies plain JSON request body", () => {
269269
const body = {
270270
id: 1,
271271
petId: 2,
@@ -286,6 +286,19 @@ describe("Generated fetch request", () => {
286286
JSON.stringify(body)
287287
);
288288
});
289+
290+
it("preserves request body of FormData objects", () => {
291+
const body = new FormData();
292+
293+
customFetch("/store/order", {
294+
method: "post",
295+
headers: { Accept: "nothing" },
296+
integrity: "dummy",
297+
body: body,
298+
});
299+
300+
expect((mockedFetch.mock.calls[0] as any)[1].body).toBe(body);
301+
});
289302
});
290303

291304
describe("Generated fetch response", () => {

0 commit comments

Comments
 (0)