Skip to content

Commit

Permalink
feat(hotfix): allow constructFullUrlWithParams to receive a rel path …
Browse files Browse the repository at this point in the history
…or full url
  • Loading branch information
ribeirojose committed Apr 11, 2024
1 parent 3f4bbfa commit 9b5e3fa
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 5 deletions.
4 changes: 2 additions & 2 deletions src/components/DataTable/useSWRDataTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ function formatRequestParams(originalObj) {
};
}

const dataTableFetcher = async ([url, paramsObject]) => {
const dataTableFetcher = async ([pathOrUrl, paramsObject]) => {
const formattedParams = formatRequestParams(paramsObject);

const fullUrl = constructFullUrlWithParams(url, formattedParams);
const fullUrl = constructFullUrlWithParams(pathOrUrl, formattedParams);

const response = await fetch(fullUrl, {
headers: {
Expand Down
10 changes: 7 additions & 3 deletions src/lib/constructFullUrlWithParams.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import { deserializeQuery, serializeQuery } from "./serializeQuery";

export function constructFullUrlWithParams(
baseUrl: string,
pathOrUrl: string,
queryParams: Record<string, unknown>
) {
if (typeof baseUrl !== "string") {
if (typeof pathOrUrl !== "string") {
throw new Error("Base URL must be a string.");
}

const url = new URL(baseUrl, window.location.origin);
const isFullUrl = /^(http|https):\/\//.test(pathOrUrl);
const url = new URL(
pathOrUrl,
isFullUrl ? undefined : window.location.origin
);

const existingParams = deserializeQuery(url.search);

Expand Down
16 changes: 16 additions & 0 deletions tests/lib/constructFullUrlWithParams.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,22 @@ describe("constructFullUrlWithParams", () => {
);
});

it("should correctly handle full URLs", () => {
const fullUrl = "http://example.com";
const queryParams = { section: "blog", article: 123 };
const result = constructFullUrlWithParams(fullUrl, queryParams);
expect(result).toBe("http://example.com/?section=blog&article=123");
});

it("should correctly handle relative paths", () => {
const relativePath = "/path/to/resource";
const queryParams = { section: "blog", article: 123 };
const result = constructFullUrlWithParams(relativePath, queryParams);
expect(result).toBe(
"http://localhost/path/to/resource?section=blog&article=123"
);
});

it("should correctly add simple query parameters to a base URL", () => {
const baseUrl = "http://example.com";
const queryParams = { name: "John", age: 30 };
Expand Down

0 comments on commit 9b5e3fa

Please sign in to comment.