Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Keep existing query params compared to new ones #58

Merged
merged 1 commit into from
Apr 14, 2024
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
3 changes: 2 additions & 1 deletion src/lib/constructFullUrlWithParams.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { mergeObjects } from "./mergeObjects";
import { deserializeQuery, serializeQuery } from "./serializeQuery";

export function constructFullUrlWithParams(
Expand All @@ -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;
Expand Down
17 changes: 17 additions & 0 deletions src/lib/mergeObjects.ts
Original file line number Diff line number Diff line change
@@ -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;
};
6 changes: 3 additions & 3 deletions tests/lib/constructFullUrlWithParams.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});
});