Skip to content

Commit f48c642

Browse files
committed
rewrite the dynamic routes chapter + add code samples
1 parent c5d77a9 commit f48c642

File tree

8 files changed

+595
-317
lines changed

8 files changed

+595
-317
lines changed

chapters/ch06.9-ex-dynamic-routing.md

Lines changed: 260 additions & 317 deletions
Large diffs are not rendered by default.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

src/chapter_06.7/index.js

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
const HTTP_METHODS = {
2+
GET: "GET",
3+
POST: "POST",
4+
PUT: "PUT",
5+
DELETE: "DELETE",
6+
PATCH: "PATCH",
7+
HEAD: "HEAD",
8+
OPTIONS: "OPTIONS",
9+
CONNECT: "CONNECT",
10+
TRACE: "TRACE",
11+
};
12+
13+
class RouteNode {
14+
constructor() {
15+
this.children = new Map();
16+
this.handler = new Map();
17+
}
18+
}
19+
20+
class TrieRouter {
21+
constructor() {
22+
this.root = new RouteNode();
23+
}
24+
25+
addRoute(path, method, handler) {
26+
if (typeof path !== "string" || path[0] !== "/") throw new Error("Malformed path provided.");
27+
if (typeof handler !== "function") throw new Error("Handler should be a function");
28+
if (!HTTP_METHODS[method]) throw new Error("Invalid HTTP Method");
29+
30+
let currentNode = this.root;
31+
let routeParts = path.split("/").filter(Boolean);
32+
33+
for (let idx = 0; idx < routeParts.length; idx++) {
34+
const segment = routeParts[idx].toLowerCase();
35+
if (segment.includes(" ")) throw new Error("Malformed `path` parameter");
36+
37+
let childNode = currentNode.children.get(segment);
38+
if (!childNode) {
39+
childNode = new RouteNode();
40+
currentNode.children.set(segment, childNode);
41+
}
42+
43+
currentNode = childNode;
44+
}
45+
currentNode.handler.set(method, handler); // Changed this line
46+
}
47+
48+
findRoute(path, method) {
49+
let segments = path.split("/").filter(Boolean);
50+
let currentNode = this.root;
51+
52+
for (let idx = 0; idx < segments.length; idx++) {
53+
const segment = segments[idx];
54+
55+
let childNode = currentNode.children.get(segment);
56+
if (childNode) {
57+
currentNode = childNode;
58+
} else {
59+
return null;
60+
}
61+
}
62+
63+
return currentNode.handler.get(method); // Changed this line
64+
}
65+
66+
printTree(node = this.root, indentation = 0) {
67+
const indent = "-".repeat(indentation);
68+
69+
node.children.forEach((childNode, segment) => {
70+
console.log(`${indent}${segment}`);
71+
this.printTree(childNode, indentation + 1);
72+
});
73+
}
74+
}

src/chapter_06.8/index.js

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
const HTTP_METHODS = {
2+
GET: "GET",
3+
POST: "POST",
4+
PUT: "PUT",
5+
DELETE: "DELETE",
6+
PATCH: "PATCH",
7+
HEAD: "HEAD",
8+
OPTIONS: "OPTIONS",
9+
CONNECT: "CONNECT",
10+
TRACE: "TRACE",
11+
};
12+
13+
class RouteNode {
14+
constructor() {
15+
this.children = new Map();
16+
this.handler = new Map();
17+
}
18+
}
19+
20+
class TrieRouter {
21+
constructor() {
22+
this.root = new RouteNode();
23+
}
24+
25+
#addRoute(path, method, handler) {
26+
if (typeof path !== "string" || path[0] !== "/") throw new Error("Malformed path provided.");
27+
if (typeof handler !== "function") throw new Error("Handler should be a function");
28+
if (!HTTP_METHODS[method]) throw new Error("Invalid HTTP Method");
29+
30+
let currentNode = this.root;
31+
let routeParts = path.split("/").filter(Boolean);
32+
33+
for (let idx = 0; idx < routeParts.length; idx++) {
34+
const segment = routeParts[idx].toLowerCase();
35+
if (segment.includes(" ")) throw new Error("Malformed `path` parameter");
36+
37+
let childNode = currentNode.children.get(segment);
38+
if (!childNode) {
39+
childNode = new RouteNode();
40+
currentNode.children.set(segment, childNode);
41+
}
42+
43+
currentNode = childNode;
44+
}
45+
currentNode.handler.set(method, handler); // Changed this line
46+
}
47+
48+
findRoute(path, method) {
49+
let segments = path.split("/").filter(Boolean);
50+
let currentNode = this.root;
51+
52+
for (let idx = 0; idx < segments.length; idx++) {
53+
const segment = segments[idx];
54+
55+
let childNode = currentNode.children.get(segment);
56+
if (childNode) {
57+
currentNode = childNode;
58+
} else {
59+
return null;
60+
}
61+
}
62+
63+
return currentNode.handler.get(method); // Changed this line
64+
}
65+
66+
printTree(node = this.root, indentation = 0) {
67+
const indent = "-".repeat(indentation);
68+
69+
node.children.forEach((childNode, segment) => {
70+
console.log(`${indent}${segment}`);
71+
this.printTree(childNode, indentation + 1);
72+
});
73+
}
74+
get(path, handler) {
75+
this.#addRoute(path, HTTP_METHODS.GET, handler);
76+
}
77+
78+
post(path, handler) {
79+
this.#addRoute(path, HTTP_METHODS.POST, handler);
80+
}
81+
82+
put(path, handler) {
83+
this.#addRoute(path, HTTP_METHODS.PUT, handler);
84+
}
85+
86+
delete(path, handler) {
87+
this.#addRoute(path, HTTP_METHODS.DELETE, handler);
88+
}
89+
90+
patch(path, handler) {
91+
this.#addRoute(path, HTTP_METHODS.PATCH, handler);
92+
}
93+
94+
head(path, handler) {
95+
this.#addRoute(path, HTTP_METHODS.HEAD, handler);
96+
}
97+
98+
options(path, handler) {
99+
this.#addRoute(path, HTTP_METHODS.OPTIONS, handler);
100+
}
101+
102+
connect(path, handler) {
103+
this.#addRoute(path, HTTP_METHODS.CONNECT, handler);
104+
}
105+
106+
trace(path, handler) {
107+
this.#addRoute(path, HTTP_METHODS.TRACE, handler);
108+
}
109+
}

src/chapter_06.9/index.js

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
const HTTP_METHODS = {
2+
GET: "GET",
3+
POST: "POST",
4+
PUT: "PUT",
5+
DELETE: "DELETE",
6+
PATCH: "PATCH",
7+
HEAD: "HEAD",
8+
OPTIONS: "OPTIONS",
9+
CONNECT: "CONNECT",
10+
TRACE: "TRACE",
11+
};
12+
13+
class RouteNode {
14+
constructor() {
15+
this.children = new Map();
16+
this.handler = new Map();
17+
this.params = [];
18+
}
19+
}
20+
21+
class TrieRouter {
22+
constructor() {
23+
this.root = new RouteNode();
24+
}
25+
26+
#verifyParams(path, method, handler) {
27+
if (typeof path !== "string" || path[0] !== "/") throw new Error("Malformed path provided.");
28+
if (typeof handler !== "function") throw new Error("Handler should be a function");
29+
if (!HTTP_METHODS[method]) throw new Error("Invalid HTTP Method");
30+
}
31+
32+
#addRoute(path, method, handler) {
33+
this.#verifyParams(path, method, handler);
34+
35+
let currentNode = this.root;
36+
let routeParts = path.split("/").filter(Boolean);
37+
let dynamicParams = [];
38+
39+
for (const segment of routeParts) {
40+
if (segment.includes(" ")) throw new Error("Malformed `path` parameter");
41+
42+
const isDynamic = segment[0] === ":";
43+
const key = isDynamic ? ":" : segment.toLowerCase();
44+
45+
if (isDynamic) {
46+
dynamicParams.push(segment.substring(1));
47+
}
48+
49+
if (!currentNode.children.has(key)) {
50+
currentNode.children.set(key, new RouteNode());
51+
}
52+
53+
currentNode = currentNode.children.get(key);
54+
}
55+
56+
currentNode.handler.set(method, handler);
57+
currentNode.params = dynamicParams;
58+
}
59+
60+
findRoute(path, method) {
61+
let segments = path.split("/").filter(Boolean);
62+
let currentNode = this.root;
63+
let extractedParams = [];
64+
65+
for (let idx = 0; idx < segments.length; idx++) {
66+
const segment = segments[idx];
67+
68+
let childNode = currentNode.children.get(segment.toLowerCase());
69+
if (childNode) {
70+
currentNode = childNode;
71+
} else if ((childNode = currentNode.children.get(":"))) {
72+
extractedParams.push(segment);
73+
currentNode = childNode;
74+
} else {
75+
return null;
76+
}
77+
}
78+
79+
let params = Object.create(null);
80+
81+
for (let idx = 0; idx < extractedParams.length; idx++) {
82+
let key = currentNode.params[idx];
83+
let value = extractedParams[idx];
84+
85+
params[key] = value;
86+
}
87+
88+
return {
89+
params,
90+
handler: currentNode.handler.get(method),
91+
};
92+
}
93+
94+
get(path, handler) {
95+
this.#addRoute(path, HTTP_METHODS.GET, handler);
96+
}
97+
98+
post(path, handler) {
99+
this.#addRoute(path, HTTP_METHODS.POST, handler);
100+
}
101+
102+
put(path, handler) {
103+
this.#addRoute(path, HTTP_METHODS.PUT, handler);
104+
}
105+
106+
delete(path, handler) {
107+
this.#addRoute(path, HTTP_METHODS.DELETE, handler);
108+
}
109+
110+
patch(path, handler) {
111+
this.#addRoute(path, HTTP_METHODS.PATCH, handler);
112+
}
113+
114+
head(path, handler) {
115+
this.#addRoute(path, HTTP_METHODS.HEAD, handler);
116+
}
117+
118+
options(path, handler) {
119+
this.#addRoute(path, HTTP_METHODS.OPTIONS, handler);
120+
}
121+
122+
connect(path, handler) {
123+
this.#addRoute(path, HTTP_METHODS.CONNECT, handler);
124+
}
125+
126+
trace(path, handler) {
127+
this.#addRoute(path, HTTP_METHODS.TRACE, handler);
128+
}
129+
130+
printTree(node = this.root, indentation = 0) {
131+
const indent = "-".repeat(indentation);
132+
133+
node.children.forEach((childNode, segment) => {
134+
console.log(`${indent}(${segment}) Dynamic: ${childNode.params}`);
135+
this.printTree(childNode, indentation + 1);
136+
});
137+
}
138+
}
139+
140+
const trieRouter = new TrieRouter();
141+
trieRouter.get("/users/:id/hello/there/:some/:hello", function get1() {});
142+
trieRouter.post("/users/:some/hello/there/:id/none", function post1() {});
143+
144+
console.log("Printing Tree:");
145+
trieRouter.printTree();
146+
147+
console.log("Finding Handlers:");
148+
149+
console.log(trieRouter.findRoute("/users/e/hello/there/2/3", HTTP_METHODS.GET));
150+
console.log(trieRouter.findRoute("/users/1/hello/there/2/none", HTTP_METHODS.GET));
151+
console.log(trieRouter.findRoute("/users", HTTP_METHODS.PUT));
152+
console.log(trieRouter.findRoute("/users", HTTP_METHODS.TRACE));

0 commit comments

Comments
 (0)