Skip to content
Draft
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
changeKind: fix
packages:
- "@typespec/http"
---

Fix route joining to preserve trailing `/` when it would not result in `//`
15 changes: 9 additions & 6 deletions packages/http/src/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,22 +36,25 @@ function needsSlashPrefix(fragment: string) {
);
}

function normalizeFragment(fragment: string, trimLast = false) {
function normalizeFragment(fragment: string) {
if (needsSlashPrefix(fragment)) {
// Insert the default separator
fragment = `/${fragment}`;
}

if (trimLast && fragment[fragment.length - 1] === "/") {
return fragment.slice(0, -1);
}
return fragment;
}

export function joinPathSegments(rest: string[]) {
let current = "";
for (const [index, segment] of rest.entries()) {
current += normalizeFragment(segment, index < rest.length - 1);
for (const segment of rest) {
const normalized = normalizeFragment(segment);
// Merge trailing and leading slashes to avoid double slashes
if (current.endsWith("/") && normalized.startsWith("/")) {
current += normalized.slice(1);
} else {
current += normalized;
}
}
return current;
}
Expand Down
19 changes: 19 additions & 0 deletions packages/http/test/routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,25 @@ describe("http: routes", () => {

deepStrictEqual(routes, [{ verb: "get", path: `/abc${sep}restype=container`, params: [] }]);
});

it("keeps trailing / on parent route when joining with child route", async () => {
const routes = await getRoutesFor(
`
@route("{blobName}/")
interface Container {
@put @route("${sep}some-query=true") op foo(blobName: string): void;
}
`,
);

deepStrictEqual(routes, [
{
verb: "put",
path: `/{blobName}/${sep}some-query=true`,
params: ["blobName"],
},
]);
});
});

describe("joinPathSegments", () => {
Expand Down
Loading