Skip to content

Commit

Permalink
Merge pull request #58 from bleu-fi/query-params
Browse files Browse the repository at this point in the history
Keep existing query params compared to new ones
  • Loading branch information
luizakp authored Apr 14, 2024
2 parents 735bdd0 + 21f8454 commit ac85629
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
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");
});
});

0 comments on commit ac85629

Please sign in to comment.