1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00
next.js/server/router.js
Naoyuki Kanezawa e3e0a68b9a Fix handling http methods (#748)
* support HEAD method

* respond with 501 if method is not GET or HEAD
2017-01-12 07:38:43 -08:00

32 lines
661 B
JavaScript

import { parse } from 'url'
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)
}
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)
}
}
}
}
}