Skip to content

Commit e42e2eb

Browse files
authored
feat(plantae): respect json type of original request body (#34)
1 parent 0571bb8 commit e42e2eb

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

.changeset/wicked-rice-switch.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"plantae": patch
3+
---
4+
5+
feat(plantae): respect json type of original request body

packages/plantae/src/axios/createAxiosInterceptors.spec.ts

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -508,4 +508,54 @@ describe("createAxiosInterceptors", () => {
508508

509509
expect(res.data).toBe("retried");
510510
});
511+
512+
it("should respect json type of original request body", async () => {
513+
server.use(
514+
http.post(base("/"), () => {
515+
return new Response();
516+
})
517+
);
518+
519+
const axios = Axios.create({
520+
baseURL,
521+
});
522+
523+
const { request } = createAxiosInterceptors({
524+
client: axios,
525+
plugins: [
526+
{
527+
name: "plugin-modify-body",
528+
hooks: {
529+
beforeRequest: async (req) => {
530+
return new Request(req, {
531+
body: JSON.stringify({ ...(await req.json()), modified: true }),
532+
});
533+
},
534+
},
535+
},
536+
],
537+
});
538+
539+
let type: string | undefined;
540+
let data: any;
541+
542+
axios.interceptors.request.use((config) => {
543+
type = typeof config.data;
544+
data = config.data;
545+
546+
return config;
547+
});
548+
549+
axios.interceptors.request.use(request.onFulfilled, request.onRejected);
550+
551+
await axios.post("/", {
552+
foo: "bar",
553+
});
554+
555+
expect(type).toBe("object");
556+
expect(data).toEqual({
557+
foo: "bar",
558+
modified: true,
559+
});
560+
});
511561
});

packages/plantae/src/axios/createAxiosInterceptors.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,13 +69,17 @@ async function extendClientRequest(
6969
): Promise<InternalAxiosRequestConfig> {
7070
let data = clientRequest.data;
7171

72+
const isJSONBody = typeof data === "object" && data !== null;
73+
7274
const { headers } = adapterRequest;
7375

7476
const contentType = headers.get("Content-Type");
7577

7678
if (adapterRequest.body) {
7779
if (contentType?.includes("multipart/form-data")) {
7880
data = await adapterRequest.formData();
81+
} else if (contentType?.includes("application/json") && isJSONBody) {
82+
data = await adapterRequest.json();
7983
} else if (
8084
contentType?.includes("application/x-www-form-urlencoded") ||
8185
contentType?.includes("text/plain") ||

0 commit comments

Comments
 (0)