2018-02-01 18:54:09 +00:00
|
|
|
import pathMatch from './lib/path-match'
|
2016-10-05 23:52:50 +00:00
|
|
|
|
2018-10-01 14:31:47 +00:00
|
|
|
export const route = pathMatch()
|
2016-10-05 23:52:50 +00:00
|
|
|
|
|
|
|
export default class Router {
|
2018-10-01 14:31:47 +00:00
|
|
|
constructor (routes = []) {
|
|
|
|
this.routes = routes
|
2016-10-05 23:52:50 +00:00
|
|
|
}
|
|
|
|
|
2018-10-01 14:31:47 +00:00
|
|
|
add (route) {
|
|
|
|
this.routes.unshift(route)
|
2016-10-05 23:52:50 +00:00
|
|
|
}
|
|
|
|
|
2017-02-02 06:51:08 +00:00
|
|
|
match (req, res, parsedUrl) {
|
2018-10-01 14:31:47 +00:00
|
|
|
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
|
|
return
|
|
|
|
}
|
2016-10-05 23:52:50 +00:00
|
|
|
|
2017-02-02 06:51:08 +00:00
|
|
|
const { pathname } = parsedUrl
|
2018-10-01 14:31:47 +00:00
|
|
|
for (const route of this.routes) {
|
|
|
|
const params = route.match(pathname)
|
2016-10-05 23:52:50 +00:00
|
|
|
if (params) {
|
2018-10-01 14:31:47 +00:00
|
|
|
return () => route.fn(req, res, params, parsedUrl)
|
2016-10-05 23:52:50 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|