2019-05-13 15:40:24 +02:00
|
|
|
import { IncomingMessage, ServerResponse } from 'http'
|
|
|
|
import { UrlWithParsedQuery } from 'url'
|
2018-12-09 22:46:45 +01:00
|
|
|
import pathMatch from './lib/path-match'
|
|
|
|
|
|
|
|
export const route = pathMatch()
|
|
|
|
|
2019-06-27 18:01:36 +02:00
|
|
|
export type Params = { [param: string]: any }
|
2018-12-09 22:46:45 +01:00
|
|
|
|
2019-05-27 20:20:33 +02:00
|
|
|
export type RouteMatch = (pathname: string | undefined) => false | Params
|
|
|
|
|
2018-12-09 22:46:45 +01:00
|
|
|
export type Route = {
|
2019-05-27 20:20:33 +02:00
|
|
|
match: RouteMatch
|
2019-05-13 15:40:24 +02:00
|
|
|
fn: (
|
|
|
|
req: IncomingMessage,
|
|
|
|
res: ServerResponse,
|
|
|
|
params: Params,
|
2019-05-29 13:57:26 +02:00
|
|
|
parsedUrl: UrlWithParsedQuery
|
|
|
|
) => void
|
2018-12-09 22:46:45 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
export default class Router {
|
|
|
|
routes: Route[]
|
2018-12-31 14:44:27 +01:00
|
|
|
constructor(routes: Route[] = []) {
|
2018-12-09 22:46:45 +01:00
|
|
|
this.routes = routes
|
|
|
|
}
|
|
|
|
|
2018-12-31 14:44:27 +01:00
|
|
|
add(route: Route) {
|
2018-12-09 22:46:45 +01:00
|
|
|
this.routes.unshift(route)
|
|
|
|
}
|
|
|
|
|
2019-05-13 15:40:24 +02:00
|
|
|
match(
|
|
|
|
req: IncomingMessage,
|
|
|
|
res: ServerResponse,
|
2019-05-29 13:57:26 +02:00
|
|
|
parsedUrl: UrlWithParsedQuery
|
2019-05-13 15:40:24 +02:00
|
|
|
) {
|
2018-12-09 22:46:45 +01:00
|
|
|
const { pathname } = parsedUrl
|
|
|
|
for (const route of this.routes) {
|
|
|
|
const params = route.match(pathname)
|
|
|
|
if (params) {
|
|
|
|
return () => route.fn(req, res, params, parsedUrl)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|