Skip to content
Open
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
17 changes: 13 additions & 4 deletions src/utils.url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,15 @@ export function joinURL(base?: string, path?: string): string {
* Adds the base path to the input path, if it is not already present.
*/
export function withBase(input = "", base = ""): string {
if (!base || base === "/") {
if (!base) {
return input;
}
const cleanedBase = String(base).trim();
if (cleanedBase === "/") {
return input;
}

const _base = withoutTrailingSlash(base);
const _base = withoutTrailingSlash(cleanedBase);
if (input.startsWith(_base)) {
return input;
}
Expand All @@ -51,11 +55,16 @@ export function withBase(input = "", base = ""): string {
}

function withoutTrailingSlash(path?: string): string {
if (!path || path === "/") {
if (!path) {
return "/";
}

const trimmed = path.trimEnd();
if (trimmed === "/") {
return "/";
}

return path[path.length - 1] === "/" ? path.slice(0, -1) : path;
return trimmed[trimmed.length - 1] === "/" ? trimmed.slice(0, -1) : trimmed;
}

/**
Expand Down
10 changes: 10 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,16 @@ describe("ofetch", () => {
);
});

it("baseURL with trailing CR", async () => {
expect(
await $fetch("/x?foo=123", { baseURL: getURL("url") + "\r" })
).to.equal("/url/x?foo=123");

expect(await $fetch("/x", { baseURL: getURL("url") + "\r" })).to.equal(
"/url/x"
);
});

it("stringifies posts body automatically", async () => {
const { body } = await $fetch(getURL("post"), {
method: "POST",
Expand Down