bun-router 0.3.7 → 0.3.9
Sign up to get free protection for your applications and to get access to all the features.
- package/examples/dynamic.ts +28 -0
- package/index.ts +3 -1
- package/lib/router/router.ts +12 -5
- package/package.json +1 -1
- package/index.d.ts +0 -2
@@ -0,0 +1,28 @@
|
|
1
|
+
import { router, html, Context } from '..';
|
2
|
+
|
3
|
+
const handler = (ctx: Context) => {
|
4
|
+
const name = ctx.params.get('name');
|
5
|
+
if (typeof name === 'undefined' || name === '') return html('<h6 style="color: red">User Undefined</h6>');
|
6
|
+
return html(`<h4>Hello, ${name}!</h4>`);
|
7
|
+
}
|
8
|
+
|
9
|
+
const space = (ctx: Context) => {
|
10
|
+
const name = ctx.params.get('name');
|
11
|
+
if (typeof name === 'undefined' || name === '') return html(`<h6 style="color: red">Space [${name}] Not Found</h6>`);
|
12
|
+
return html(`<h4>Welcome to ${name}!`)
|
13
|
+
}
|
14
|
+
|
15
|
+
const handleSettings = (ctx: Context) => {
|
16
|
+
const name = ctx.params.get('name');
|
17
|
+
if (typeof name === 'undefined' || name === '') return html(`<h6 style="color: red">User Not Found</h6>`);
|
18
|
+
return html(`<h4>Settings for ${name}</h4>`)
|
19
|
+
}
|
20
|
+
|
21
|
+
const r = router();
|
22
|
+
|
23
|
+
r.add('/u/:name', 'GET', handler);
|
24
|
+
r.add('/s/:name', 'GET', space);
|
25
|
+
r.add('/u/:name/settings', 'GET', handleSettings);
|
26
|
+
|
27
|
+
|
28
|
+
r.serve();
|
package/index.ts
CHANGED
package/lib/router/router.ts
CHANGED
@@ -99,7 +99,18 @@ const extract = (route: Route, ctx: Context) => {
|
|
99
99
|
}
|
100
100
|
|
101
101
|
const match = (route: Route, ctx: Context): boolean => {
|
102
|
-
|
102
|
+
const url = new URL(ctx.request.url);
|
103
|
+
const patternRegex = new RegExp('^' + route.pattern.replace(/:[^/]+/g, '([^/]+)') + '$');
|
104
|
+
const matches = url.pathname.match(patternRegex);
|
105
|
+
|
106
|
+
if (matches) {
|
107
|
+
const extractor = extract(route, ctx);
|
108
|
+
extractor?.params();
|
109
|
+
|
110
|
+
return true;
|
111
|
+
}
|
112
|
+
|
113
|
+
return false;
|
103
114
|
}
|
104
115
|
|
105
116
|
const router: Router = (port?: number | string, options?: Options) => {
|
@@ -155,10 +166,6 @@ const router: Router = (port?: number | string, options?: Options) => {
|
|
155
166
|
fs: new Map(),
|
156
167
|
};
|
157
168
|
|
158
|
-
const extractor = extract(route, ctx);
|
159
|
-
|
160
|
-
extractor?.params();
|
161
|
-
|
162
169
|
if (url.pathname === '/favicon.ico') return noContent();
|
163
170
|
|
164
171
|
if (match(route, ctx)) {
|
package/package.json
CHANGED
package/index.d.ts
DELETED