rsnext/packages/next-server/server/router.ts
Lukáš Huvar b5e3aac1ec Fix POST and PUT on api routes (#7319)
* Fix POST and PUT

* Fix condition for request and test
2019-05-13 15:40:23 +02:00

42 lines
913 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 Route = {
match: (pathname: string | undefined) => false | Params
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)
}
}
}
}