Skip to content

Commit

Permalink
feat: smart url merger
Browse files Browse the repository at this point in the history
  • Loading branch information
Bekacru committed Jul 25, 2024
1 parent 1f32020 commit e670022
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
42 changes: 42 additions & 0 deletions packages/better-fetch/src/test/create.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,48 @@ describe("create-fetch-runtime-test", () => {
listener.close().catch(console.error);
});

it("should merge baseURL and url", async () => {
const $fetch = createFetch({
baseURL: "http://localhost:4001",
schema: createSchema(schema),
customFetchImpl: async (req, init) => {
return new Response(null, {
status: 200,
});
},
});
$fetch("/echo", {
baseURL: "http://localhost:4001",
body: { id: 1 },
onRequest(context) {
expect(context.url.toString()).toBe("http://localhost:4001/echo");
},
});
$fetch("/path", {
baseURL: "http://localhost:4001/v1",
body: { id: 1 },
onRequest(context) {
expect(context.url.toString()).toBe("http://localhost:4001/v1/path");
},
});

$fetch("/path", {
baseURL: "http://localhost:4001/v1/",
body: { id: 1 },
onRequest(context) {
expect(context.url.toString()).toBe("http://localhost:4001/v1/path");
},
});

$fetch("/path/", {
baseURL: "http://localhost:4001/v1/",
body: { id: 1 },
onRequest(context) {
expect(context.url.toString()).toBe("http://localhost:4001/v1/path/");
},
});
});

it("should validate response and throw if validation fails", async () => {
expect(
$fetch("/post", {
Expand Down
15 changes: 13 additions & 2 deletions packages/better-fetch/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,19 @@ export function getURL(url: string, options?: BetterFetchOption) {
}
let _url: string | URL;
try {
_url = url.startsWith("http") ? url : new URL(url, options?.baseURL);
if (url.startsWith("http")) {
_url = url;
} else {
let baseURL = options?.baseURL;
if (baseURL && !baseURL?.endsWith("/")) {
baseURL = baseURL + "/";
}
if (url.startsWith("/")) {
_url = new URL(url.substring(1), baseURL);
} else {
_url = new URL(url, options?.baseURL);
}
}
} catch (e) {
if (e instanceof TypeError) {
if (!options?.baseURL) {
Expand Down Expand Up @@ -168,7 +180,6 @@ export function getURL(url: string, options?: BetterFetchOption) {
__url.searchParams.append(key, String(value));
}
}

return __url;
}

Expand Down

0 comments on commit e670022

Please sign in to comment.