diff --git a/src/lib/constructFullUrlWithParams.ts b/src/lib/constructFullUrlWithParams.ts index ce666ef..4890821 100644 --- a/src/lib/constructFullUrlWithParams.ts +++ b/src/lib/constructFullUrlWithParams.ts @@ -1,3 +1,4 @@ +import { mergeObjects } from "./mergeObjects"; import { deserializeQuery, serializeQuery } from "./serializeQuery"; export function constructFullUrlWithParams( @@ -16,7 +17,7 @@ export function constructFullUrlWithParams( const existingParams = deserializeQuery(url.search); - const mergedParams = { ...existingParams, ...queryParams }; + const mergedParams = mergeObjects(existingParams, queryParams); const serializedParams = serializeQuery(mergedParams); url.search = serializedParams; diff --git a/src/lib/mergeObjects.ts b/src/lib/mergeObjects.ts new file mode 100644 index 0000000..238e136 --- /dev/null +++ b/src/lib/mergeObjects.ts @@ -0,0 +1,17 @@ +export const mergeObjects = (existing, incoming) => { + const result = { ...existing }; + + Object.keys(incoming).forEach((key) => { + if ( + key in result && + typeof result[key] === "object" && + typeof incoming[key] === "object" + ) { + result[key] = mergeObjects(result[key], incoming[key]); + } else if (!(key in result)) { + result[key] = incoming[key]; + } + }); + + return result; +}; diff --git a/tests/lib/constructFullUrlWithParams.test.ts b/tests/lib/constructFullUrlWithParams.test.ts index 98349c0..8e9fd36 100644 --- a/tests/lib/constructFullUrlWithParams.test.ts +++ b/tests/lib/constructFullUrlWithParams.test.ts @@ -61,13 +61,13 @@ describe("constructFullUrlWithParams", () => { const baseUrl = "http://example.com?name=Jane&active=true"; const queryParams = { age: 30, active: false }; const result = constructFullUrlWithParams(baseUrl, queryParams); - expect(result).toBe("http://example.com/?name=Jane&active=false&age=30"); + expect(result).toBe("http://example.com/?name=Jane&active=true&age=30"); }); - it("should override existing parameters with new ones", () => { + it("should not override existing parameters with new ones", () => { const baseUrl = "http://example.com?name=Jane"; const queryParams = { name: "John", age: 30 }; const result = constructFullUrlWithParams(baseUrl, queryParams); - expect(result).toBe("http://example.com/?name=John&age=30"); + expect(result).toBe("http://example.com/?name=Jane&age=30"); }); });