Skip to content

Commit 972f7a7

Browse files
committed
feat: 라우터 initRoutes 옵션 추가
1 parent 4d35094 commit 972f7a7

File tree

2 files changed

+35
-5
lines changed

2 files changed

+35
-5
lines changed

packages/lib/src/router/SPARouter.ts

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,9 +60,13 @@ export class SPARouter<Handler extends AnyFunction> {
6060
private readonly baseUrl;
6161
private currentRoute: CurrentRouter<Handler> | null = null;
6262

63-
constructor(baseUrl = "") {
63+
constructor(initRoutes: Record<string, Handler>, baseUrl = "") {
6464
this.baseUrl = baseUrl.replace(/\/$/, "");
6565

66+
Object.entries(initRoutes).forEach(([path, page]) => {
67+
this.addRoute(path, page);
68+
});
69+
6670
window.addEventListener("popstate", () => {
6771
this.currentRoute = this.findRoute();
6872
this.observer.notify();
@@ -105,6 +109,17 @@ export class SPARouter<Handler extends AnyFunction> {
105109
}
106110

107111
public addRoute(path: string, handler: Handler) {
112+
if (path === "*") {
113+
const regex = new RegExp(".*");
114+
this.routes.set(path, {
115+
regex,
116+
paramNames: [],
117+
handler,
118+
});
119+
120+
return;
121+
}
122+
108123
// 경로 패턴을 정규식으로 변환
109124
const paramNames: string[] = [];
110125
const regexPath = path
@@ -141,8 +156,8 @@ export class SPARouter<Handler extends AnyFunction> {
141156
}
142157
}
143158

144-
public start() {
145-
this.currentRoute = this.findRoute();
159+
public start(url?: string) {
160+
this.currentRoute = this.findRoute(url);
146161
this.observer.notify();
147162
}
148163

packages/lib/src/router/ServerRouter.ts

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,12 @@ export class ServerRouter<Handler extends AnyFunction> {
5959
private currentRoute: CurrentRouter<Handler> | null = null;
6060
private currentUrl = "/";
6161

62-
constructor(baseUrl = "") {
62+
constructor(initRoutes: Record<string, Handler>, baseUrl = "") {
6363
this.baseUrl = baseUrl.replace(/\/$/, "");
64+
65+
Object.entries(initRoutes).forEach(([path, page]) => {
66+
this.addRoute(path, page);
67+
});
6468
}
6569

6670
get query(): StringRecord {
@@ -93,6 +97,17 @@ export class ServerRouter<Handler extends AnyFunction> {
9397
}
9498

9599
public addRoute(path: string, handler: Handler) {
100+
if (path === "*") {
101+
const regex = new RegExp(".*");
102+
this.routes.set(path, {
103+
regex,
104+
paramNames: [],
105+
handler,
106+
});
107+
108+
return;
109+
}
110+
96111
// 경로 패턴을 정규식으로 변환
97112
const paramNames: string[] = [];
98113
const regexPath = path
@@ -102,7 +117,7 @@ export class ServerRouter<Handler extends AnyFunction> {
102117
})
103118
.replace(/\//g, "\\/");
104119

105-
const regex = new RegExp(`^${this.baseUrl}${regexPath}$`);
120+
const regex = new RegExp(`^${regexPath}$`);
106121

107122
this.routes.set(path, {
108123
regex,

0 commit comments

Comments
 (0)