Skip to content
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
23 changes: 23 additions & 0 deletions packages/better-fetch/src/test/fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -601,3 +601,26 @@ describe("url", () => {
expect(url.toString()).toBe("http://localhost:4000/test?foo=bar");
});
});

describe("form data", async () => {
it("should parse json to form data", async () => {
const { data } = await betterFetch("/echo", {
body: {
name: "John Doe",
age: 30,
},
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
onRequest(context) {
console.log(context.body);
},
customFetchImpl: async (req, init) => {
return new Response(JSON.stringify(init?.body), {
status: 200,
});
},
});
expect(data).toBe("name=John+Doe&age=30");
});
});
12 changes: 11 additions & 1 deletion packages/better-fetch/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,16 @@ export function getBody(options?: BetterFetchOption) {
return JSON.stringify(options.body);
}

if (
headers.has("content-type") &&
headers.get("content-type") === "application/x-www-form-urlencoded"
) {
if (isJSONSerializable(options.body)) {
return new URLSearchParams(options.body).toString();
}
return options.body;
}

return options.body;
}

Expand Down Expand Up @@ -265,7 +275,7 @@ export async function parseStandardSchema<TSchema extends StandardSchemaV1>(
schema: TSchema,
input: StandardSchemaV1.InferInput<TSchema>,
): Promise<StandardSchemaV1.InferOutput<TSchema>> {
let result = await schema["~standard"].validate(input);
const result = await schema["~standard"].validate(input);

if (result.issues) {
throw new ValidationError(result.issues);
Expand Down