-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathServerRouter.ts
More file actions
142 lines (119 loc) · 3.78 KB
/
ServerRouter.ts
File metadata and controls
142 lines (119 loc) · 3.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import type { AnyFunction, StringRecord } from "./types";
import { createObserver } from "./createObserver";
interface Route<Handler extends AnyFunction> {
regex: RegExp;
paramNames: string[];
handler: Handler;
params?: StringRecord;
}
type QueryPayload = Record<string, string | number | undefined>;
export type RouterInstance<T extends AnyFunction> = InstanceType<typeof ServerRouter<T>>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export class ServerRouter<Handler extends (...args: any[]) => any> {
readonly #routes: Map<string, Route<Handler>>;
readonly #observer = createObserver();
readonly #baseUrl;
#currentQuery: StringRecord;
#route: null | (Route<Handler> & { params: StringRecord; path: string });
constructor(baseUrl = "") {
this.#routes = new Map();
this.#route = null;
this.#baseUrl = baseUrl.replace(/\/$/, "");
this.#currentQuery = {};
}
get query(): StringRecord {
return this.#currentQuery;
}
set query(newQuery: QueryPayload) {
const pathname = this.#route?.path ?? "/";
const newUrl = ServerRouter.getUrl(newQuery, pathname, this.#baseUrl);
this.push(newUrl);
}
get params() {
return this.#route?.params ?? {};
}
get route() {
return this.#route;
}
get target() {
return this.#route?.handler;
}
addRoute(path: string, handler: Handler) {
// 경로 패턴을 정규식으로 변환
const paramNames: string[] = [];
const regexPath = path
.replace(/:\w+/g, (match) => {
paramNames.push(match.slice(1)); // ':id' -> 'id'
return "([^/]+)";
})
.replace(/\//g, "\\/");
const regex = new RegExp(`^${this.#baseUrl}${regexPath}$`);
this.#routes.set(path, {
regex,
paramNames,
handler,
});
}
#findRoute(url = "/", origin = "http://localhost") {
const { pathname } = new URL(url, origin);
for (const [routePath, route] of this.#routes) {
const match = pathname.match(route.regex);
if (match) {
// 매치된 파라미터들을 객체로 변환
const params: StringRecord = {};
route.paramNames.forEach((name, index) => {
params[name] = match[index + 1];
});
return {
...route,
params,
path: routePath,
};
}
}
return null;
}
push(url: string = "/") {
try {
this.#route = this.#findRoute(url);
} catch (error) {
console.error("라우터 네비게이션 오류:", error);
}
}
start(url = "/", query = {}) {
this.#route = this.#findRoute(url);
this.#currentQuery = query;
}
subscribe = (listener: () => void) => {
return this.#observer.subscribe(listener);
};
static parseQuery = (search: string = "") => {
const params = new URLSearchParams(search);
const query: StringRecord = {};
for (const [key, value] of params) {
query[key] = value;
}
return query;
};
static stringifyQuery = (query: QueryPayload) => {
const params = new URLSearchParams();
for (const [key, value] of Object.entries(query)) {
if (value !== null && value !== undefined && value !== "") {
params.set(key, String(value));
}
}
return params.toString();
};
static getUrl = (newQuery: QueryPayload, pathname = "/", baseUrl = "") => {
const currentQuery = ServerRouter.parseQuery();
const updatedQuery = { ...currentQuery, ...newQuery };
// 빈 값들 제거
Object.keys(updatedQuery).forEach((key) => {
if (updatedQuery[key] === null || updatedQuery[key] === undefined || updatedQuery[key] === "") {
delete updatedQuery[key];
}
});
const queryString = ServerRouter.stringifyQuery(updatedQuery);
return `${baseUrl}${pathname.replace(baseUrl, "")}${queryString ? `?${queryString}` : ""}`;
};
}