diff --git a/.changeset/witty-sheep-mix.md b/.changeset/witty-sheep-mix.md new file mode 100644 index 000000000..c3025aaa3 --- /dev/null +++ b/.changeset/witty-sheep-mix.md @@ -0,0 +1,5 @@ +--- +"openapi-fetch": patch +--- + +Fix behavior for empty arrays and objects in default `querySerializer` diff --git a/packages/openapi-fetch/src/index.ts b/packages/openapi-fetch/src/index.ts index f079b2fd2..95e00ee2b 100644 --- a/packages/openapi-fetch/src/index.ts +++ b/packages/openapi-fetch/src/index.ts @@ -305,7 +305,7 @@ export function defaultQuerySerializer(q: T): string { if (q && typeof q === "object") { for (const [k, v] of Object.entries(q)) { const value = defaultQueryParamSerializer([k], v); - if (value !== undefined) { + if (value) { search.push(value); } } @@ -328,6 +328,9 @@ export function defaultQueryParamSerializer( return `${deepObjectPath(key)}=${String(value)}`; } if (Array.isArray(value)) { + if (!value.length) { + return undefined; + } const nextValue: string[] = []; for (const item of value) { const next = defaultQueryParamSerializer(key, item); @@ -338,6 +341,9 @@ export function defaultQueryParamSerializer( return nextValue.join(`&`); } if (typeof value === "object") { + if (!Object.keys(value).length) { + return undefined; + } const nextValue: string[] = []; for (const [k, v] of Object.entries(value)) { if (v !== undefined && v !== null) { diff --git a/packages/openapi-fetch/test/index.test.ts b/packages/openapi-fetch/test/index.test.ts index 19b6a9b10..8e0359675 100644 --- a/packages/openapi-fetch/test/index.test.ts +++ b/packages/openapi-fetch/test/index.test.ts @@ -185,6 +185,18 @@ describe("client", () => { ); }); + it("array params (empty)", async () => { + const client = createClient(); + mockFetchOnce({ status: 200, body: "{}" }); + await client.GET("/query-params", { + params: { + query: { array: [] }, + }, + }); + + expect(fetchMocker.mock.calls[0][0]).toBe("/query-params"); + }); + it("object params", async () => { const client = createClient(); mockFetchOnce({ status: 200, body: "{}" }); diff --git a/packages/openapi-fetch/test/v7-beta.test.ts b/packages/openapi-fetch/test/v7-beta.test.ts index 6ec419534..9c7308dc6 100644 --- a/packages/openapi-fetch/test/v7-beta.test.ts +++ b/packages/openapi-fetch/test/v7-beta.test.ts @@ -194,6 +194,18 @@ describe("client", () => { ); }); + it("array params (empty)", async () => { + const client = createClient(); + mockFetchOnce({ status: 200, body: "{}" }); + await client.GET("/query-params", { + params: { + query: { array: [] }, + }, + }); + + expect(fetchMocker.mock.calls[0][0]).toBe("/query-params"); + }); + it("object params", async () => { const client = createClient(); mockFetchOnce({ status: 200, body: "{}" });