Skip to content

Commit 7c7d31b

Browse files
committed
feat: support duplicate base path handling in router
1 parent 8b6f13e commit 7c7d31b

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

src/router.test.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,25 @@ describe("router", () => {
183183
const response = await router.handler(new Request("http://localhost"));
184184
expect(response.status).toBe(403);
185185
});
186+
187+
it("should work with duplicate base path", async () => {
188+
const endpoint = createEndpoint(
189+
"/test/api/v1/test",
190+
{
191+
method: "GET",
192+
},
193+
async (c) => {
194+
return c.path;
195+
},
196+
);
197+
const router = createRouter({ endpoint }, { basePath: "/api/v1" });
198+
const response = await router.handler(
199+
new Request("http://localhost/api/v1/test/api/v1/test"),
200+
);
201+
expect(response.status).toBe(200);
202+
const text = await response.text();
203+
expect(text).toBe("/test/api/v1/test");
204+
});
186205
});
187206

188207
describe("route middleware", () => {

src/router.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,21 @@ export const createRouter = <E extends Record<string, Endpoint>, Config extends
123123

124124
const processRequest = async (request: Request) => {
125125
const url = new URL(request.url);
126-
const path = config?.basePath ? url.pathname.split(config.basePath)[1] : url.pathname;
126+
const path = config?.basePath
127+
? url.pathname
128+
.split(config.basePath)
129+
.reduce((acc, curr, index) => {
130+
if (index !== 0) {
131+
if (index > 1) {
132+
acc.push(`${config.basePath}${curr}`);
133+
} else {
134+
acc.push(curr);
135+
}
136+
}
137+
return acc;
138+
}, [] as string[])
139+
.join("")
140+
: url.pathname;
127141

128142
if (!path?.length) {
129143
return new Response(null, { status: 404, statusText: "Not Found" });

0 commit comments

Comments
 (0)