Skip to content

Commit

Permalink
Add trailingSlash option to route
Browse files Browse the repository at this point in the history
fix #168
  • Loading branch information
tatethurston committed May 27, 2024
1 parent 1f7358d commit e8a5178
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
27 changes: 27 additions & 0 deletions packages/nextjs-routes/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,31 @@ describe(route, () => {
}),
).toEqual("/foos/foo?bar=bar&baz=1&baz=2&baz=3#foo");
});

describe("options", () => {
describe("trailingSlash", () => {
it("when true", () => {
expect(
route({ pathname: "/settings/about" }, { trailingSlash: true }),
).toEqual("/settings/about/");
expect(
route(
{ pathname: "/foos/[foo]", query: { foo: "bar" } },
{ trailingSlash: true },
),
).toEqual("/foos/bar/");
});
it("when false", () => {
expect(
route({ pathname: "/settings/about" }, { trailingSlash: false }),
).toEqual("/settings/about");
expect(
route(
{ pathname: "/foos/[foo]", query: { foo: "bar" } },
{ trailingSlash: false },
),
).toEqual("/foos/bar");
});
});
});
});
15 changes: 13 additions & 2 deletions packages/nextjs-routes/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,16 @@ interface Dynamic extends Route {
query: { [key: string]: string };
}

export function route(r: Route): string {
interface RouteOptions {
trailingSlash?: boolean;
}

export function route(
r: Route,
options: RouteOptions = { trailingSlash: false },
): string {
const params = new Set<string>();
const path =
let path =
"/" +
r.pathname
.split("/")
Expand Down Expand Up @@ -47,6 +54,10 @@ export function route(r: Route): string {
.filter(Boolean)
.join("/");

if (options.trailingSlash) {
path += "/";
}

const search = new URLSearchParams();
for (const key in r.query) {
if (!params.has(key)) {
Expand Down

0 comments on commit e8a5178

Please sign in to comment.