forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.js
More file actions
35 lines (29 loc) · 715 Bytes
/
router.js
File metadata and controls
35 lines (29 loc) · 715 Bytes
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
import { parse } from 'url'
import pathMatch from 'path-match'
const route = pathMatch()
export default class Router {
constructor () {
this.routes = new Map()
}
get (path, fn) {
this.add('GET', path, fn)
}
add (method, path, fn) {
const routes = this.routes.get(method) || new Set()
routes.add({ match: route(path), fn })
this.routes.set(method, routes)
}
match (req, res) {
const routes = this.routes.get(req.method)
if (!routes) return
const { pathname } = parse(req.url)
for (const r of routes) {
const params = r.match(pathname)
if (params) {
return async () => {
return r.fn(req, res, params)
}
}
}
}
}