Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: support for routes with file extensions #46

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 24 additions & 0 deletions packages/routes-gen/src/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,27 @@ it("only replaces the first occurrence when param names share the same prefix",
route("/podcasts/:topicId/:topic", { topic: "sports", topicId: "123" })
).toEqual("/podcasts/123/sports");
});

it('should return the same path when no params are provided', () => {
expect(route("/test")).toEqual("/test");
});

it('should replace :id with provided id', () => {
expect(route("/:id", { id: "test" })).toEqual("/test");
expect(route("/:id", { id: 1 })).toEqual("/1");
});

it('should replace :id with provided id in a path with file extension', () => {
expect(route("/:id.pdf", { id: "test" })).toEqual("/test.pdf");
expect(route("/:id.pdf", { id: 1 })).toEqual("/1.pdf");
});

it('should replace :id with provided id in a nested path', () => {
expect(route("/test/:id", { id: "test" })).toEqual("/test/test");
expect(route("/test/:id", { id: 1 })).toEqual("/test/1");
});

it('should replace :id with provided id in a nested path with file extension', () => {
expect(route("/test/:id.pdf", { id: "test" })).toEqual("/test/test.pdf");
expect(route("/test/:id.pdf", { id: 1 })).toEqual("/test/1.pdf");
});
7 changes: 4 additions & 3 deletions packages/routes-gen/src/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ export function route<T extends string>(
if (params) {
const segments = path.split(/\/+/).map((segment) => {
if (segment.startsWith(":")) {
const key = segment.replace(":", "").replace("?", "");
const [segmentKey, extension] = segment.split(".");
const key = segmentKey.replace(":", "").replace("?", "");

if (key in params) {
return params[key];
return extension ? `${params[key]}.${extension}` : params[key];
}

// If the segment is optional and it doesn't exist in params, return null to omit it from the resulting path
// If the segment is optional, and it doesn't exist in params, return null to omit it from the resulting path
if (segment.endsWith("?")) {
return null;
}
Expand Down