rsnext/packages/next-server/server/router.ts
Tim Neutkens 3e51ddb8af
Move syntax formatting to prettier (#7454)
* Run prettier over packages/**/*.js

* Run prettier over packages/**/*.ts

* Run prettier over examples

* Remove tslint

* Run prettier over examples

* Run prettier over all markdown files

* Run prettier over json files
2019-05-29 13:57:26 +02:00

44 lines
947 B
TypeScript

import { IncomingMessage, ServerResponse } from 'http'
import { UrlWithParsedQuery } from 'url'
import pathMatch from './lib/path-match'
export const route = pathMatch()
type Params = { [param: string]: any }
export type RouteMatch = (pathname: string | undefined) => false | Params
export type Route = {
match: RouteMatch
fn: (
req: IncomingMessage,
res: ServerResponse,
params: Params,
parsedUrl: UrlWithParsedQuery
) => void
}
export default class Router {
routes: Route[]
constructor(routes: Route[] = []) {
this.routes = routes
}
add(route: Route) {
this.routes.unshift(route)
}
match(
req: IncomingMessage,
res: ServerResponse,
parsedUrl: UrlWithParsedQuery
) {
const { pathname } = parsedUrl
for (const route of this.routes) {
const params = route.match(pathname)
if (params) {
return () => route.fn(req, res, params, parsedUrl)
}
}
}
}