2018-12-09 21:46:45 +00:00
|
|
|
import {IncomingMessage, ServerResponse} from 'http'
|
|
|
|
import {UrlWithParsedQuery} from 'url'
|
|
|
|
import pathMatch from './lib/path-match'
|
|
|
|
|
|
|
|
export const route = pathMatch()
|
|
|
|
|
|
|
|
type Params = {[param: string]: string}
|
|
|
|
|
|
|
|
export type Route = {
|
|
|
|
match: (pathname: string|undefined) => false|Params,
|
2018-12-31 13:44:27 +00:00
|
|
|
fn: (req: IncomingMessage, res: ServerResponse, params: Params, parsedUrl: UrlWithParsedQuery) => void,
|
2018-12-09 21:46:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export default class Router {
|
|
|
|
routes: Route[]
|
2018-12-31 13:44:27 +00:00
|
|
|
constructor(routes: Route[] = []) {
|
2018-12-09 21:46:45 +00:00
|
|
|
this.routes = routes
|
|
|
|
}
|
|
|
|
|
2018-12-31 13:44:27 +00:00
|
|
|
add(route: Route) {
|
2018-12-09 21:46:45 +00:00
|
|
|
this.routes.unshift(route)
|
|
|
|
}
|
|
|
|
|
2018-12-31 13:44:27 +00:00
|
|
|
match(req: IncomingMessage, res: ServerResponse, parsedUrl: UrlWithParsedQuery) {
|
2018-12-09 21:46:45 +00:00
|
|
|
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
const { pathname } = parsedUrl
|
|
|
|
for (const route of this.routes) {
|
|
|
|
const params = route.match(pathname)
|
|
|
|
if (params) {
|
|
|
|
return () => route.fn(req, res, params, parsedUrl)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|