2016-10-05 23:52:50 +00:00
|
|
|
import pathMatch from 'path-match'
|
|
|
|
|
|
|
|
const route = pathMatch()
|
|
|
|
|
|
|
|
export default class Router {
|
|
|
|
constructor () {
|
|
|
|
this.routes = new Map()
|
|
|
|
}
|
|
|
|
|
|
|
|
add (method, path, fn) {
|
|
|
|
const routes = this.routes.get(method) || new Set()
|
|
|
|
routes.add({ match: route(path), fn })
|
|
|
|
this.routes.set(method, routes)
|
|
|
|
}
|
|
|
|
|
2017-02-02 06:51:08 +00:00
|
|
|
match (req, res, parsedUrl) {
|
2016-10-05 23:52:50 +00:00
|
|
|
const routes = this.routes.get(req.method)
|
|
|
|
if (!routes) return
|
|
|
|
|
2017-02-02 06:51:08 +00:00
|
|
|
const { pathname } = parsedUrl
|
2016-10-05 23:52:50 +00:00
|
|
|
for (const r of routes) {
|
|
|
|
const params = r.match(pathname)
|
|
|
|
if (params) {
|
|
|
|
return async () => {
|
2017-02-02 06:51:08 +00:00
|
|
|
return r.fn(req, res, params, parsedUrl)
|
2016-10-05 23:52:50 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|