diff --git a/.changeset/wicked-rice-switch.md b/.changeset/wicked-rice-switch.md new file mode 100644 index 0000000..e214299 --- /dev/null +++ b/.changeset/wicked-rice-switch.md @@ -0,0 +1,5 @@ +--- +"plantae": patch +--- + +feat(plantae): respect json type of original request body diff --git a/packages/plantae/src/axios/createAxiosInterceptors.spec.ts b/packages/plantae/src/axios/createAxiosInterceptors.spec.ts index cf0d777..dba6096 100644 --- a/packages/plantae/src/axios/createAxiosInterceptors.spec.ts +++ b/packages/plantae/src/axios/createAxiosInterceptors.spec.ts @@ -508,4 +508,54 @@ describe("createAxiosInterceptors", () => { expect(res.data).toBe("retried"); }); + + it("should respect json type of original request body", async () => { + server.use( + http.post(base("/"), () => { + return new Response(); + }) + ); + + const axios = Axios.create({ + baseURL, + }); + + const { request } = createAxiosInterceptors({ + client: axios, + plugins: [ + { + name: "plugin-modify-body", + hooks: { + beforeRequest: async (req) => { + return new Request(req, { + body: JSON.stringify({ ...(await req.json()), modified: true }), + }); + }, + }, + }, + ], + }); + + let type: string | undefined; + let data: any; + + axios.interceptors.request.use((config) => { + type = typeof config.data; + data = config.data; + + return config; + }); + + axios.interceptors.request.use(request.onFulfilled, request.onRejected); + + await axios.post("/", { + foo: "bar", + }); + + expect(type).toBe("object"); + expect(data).toEqual({ + foo: "bar", + modified: true, + }); + }); }); diff --git a/packages/plantae/src/axios/createAxiosInterceptors.ts b/packages/plantae/src/axios/createAxiosInterceptors.ts index 35b4fc7..24fc7ef 100644 --- a/packages/plantae/src/axios/createAxiosInterceptors.ts +++ b/packages/plantae/src/axios/createAxiosInterceptors.ts @@ -69,6 +69,8 @@ async function extendClientRequest( ): Promise { let data = clientRequest.data; + const isJSONBody = typeof data === "object" && data !== null; + const { headers } = adapterRequest; const contentType = headers.get("Content-Type"); @@ -76,6 +78,8 @@ async function extendClientRequest( if (adapterRequest.body) { if (contentType?.includes("multipart/form-data")) { data = await adapterRequest.formData(); + } else if (contentType?.includes("application/json") && isJSONBody) { + data = await adapterRequest.json(); } else if ( contentType?.includes("application/x-www-form-urlencoded") || contentType?.includes("text/plain") ||