Skip to content

Commit c9a7eac

Browse files
committed
refactor: getRoutePathName with node:path
1 parent 135f065 commit c9a7eac

File tree

2 files changed

+11
-7
lines changed

2 files changed

+11
-7
lines changed

src/core/getRoutePathName.test.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { describe, expect, it } from "@jest/globals";
1+
import path from "node:path";
2+
import { describe, expect, it, jest } from "@jest/globals";
23
import getRoutePathName from "./getRoutePathName";
34

45
describe("getRoutePathName", () => {
@@ -13,9 +14,11 @@ describe("getRoutePathName", () => {
1314
});
1415

1516
it("should replace backslashes with forward slashes", () => {
17+
jest.spyOn(path, "dirname").mockReturnValueOnce("C:\\users\\omer\\Projects\\nextjs-app\\src\\app\\users\\[id]");
18+
jest.spyOn(path, "relative").mockReturnValueOnce("users\\[id]");
1619
const result = getRoutePathName(
17-
"C:\\home\\omer\\Projects\\nextjs-app\\src\\app\\users\\[id]\\route.ts",
18-
"C:\\home\\omer\\Projects\\nextjs-app\\src\\app",
20+
"C:\\users\\omer\\Projects\\nextjs-app\\src\\app\\users\\[id]\\route.ts",
21+
"C:\\users\\omer\\Projects\\nextjs-app\\src\\app",
1922
);
2023
expect(result).toBe("/users/{id}");
2124
});

src/core/getRoutePathName.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1+
import path from "node:path";
2+
13
export default function getRoutePathName(filePath: string, rootPath: string) {
2-
return filePath
3-
.replace(rootPath, "")
4+
const dirName = path.dirname(filePath);
5+
return "/" + path.relative(rootPath, dirName)
46
.replaceAll("[", "{")
57
.replaceAll("]", "}")
6-
.replaceAll("\\", "/")
7-
.replace("/route.ts", "");
8+
.replaceAll("\\", "/");
89
}

0 commit comments

Comments
 (0)