rsnext/packages/next-server/server/router.ts
Lukáš Huvar bd31c5d1b7 Dynamic routes for API (#7629)
* Dynamic routes for API

* New structure

* Change next config

* Refactoring tests

* Fix newline

* Fix tests

* Remove dynamic from config

* Apply suggestions from code review

Co-Authored-By: Joe Haddad <timer150@gmail.com>

* Update index.test.js
2019-06-27 12:01:36 -04:00

44 lines
954 B
TypeScript

import { IncomingMessage, ServerResponse } from 'http'
import { UrlWithParsedQuery } from 'url'
import pathMatch from './lib/path-match'
export const route = pathMatch()
export 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)
}
}
}
}