lib/src/http/routing/ActivatedRoute.ts

65 lines
1.8 KiB
TypeScript
Raw Normal View History

2021-06-03 03:36:25 +00:00
import {ErrorWithContext} from '../../util'
import {ResolvedRouteHandler, Route} from './Route'
import {Injectable} from '../../di'
2021-03-25 13:50:13 +00:00
/**
* Class representing a resolved route that a request is mounted to.
*/
@Injectable()
export class ActivatedRoute {
2021-03-25 13:50:13 +00:00
/**
* The parsed params from the route definition.
*
* @example
* If the route definition is like `/something/something/:paramName1/:paramName2/etc`
* and the request came in on `/something/something/foo/bar/etc`, then the params
* would be:
*
* ```typescript
* {
* paramName1: 'foo',
* paramName2: 'bar',
* }
* ```
*/
public readonly params: {[key: string]: string}
2021-03-25 13:50:13 +00:00
/**
* The resolved function that should handle the request for this route.
*/
2021-03-08 17:08:56 +00:00
public readonly handler: ResolvedRouteHandler
2021-03-25 13:50:13 +00:00
/**
* Pre-middleware that should be applied to the request on this route.
*/
2021-03-09 15:42:19 +00:00
public readonly preflight: ResolvedRouteHandler[]
2021-03-25 13:50:13 +00:00
/**
* Post-middleware that should be applied to the request on this route.
*/
2021-03-09 15:42:19 +00:00
public readonly postflight: ResolvedRouteHandler[]
constructor(
2021-03-25 13:50:13 +00:00
/** The route this ActivatedRoute refers to. */
public readonly route: Route,
2021-03-25 13:50:13 +00:00
/** The request path that activated that route. */
2021-06-03 03:36:25 +00:00
public readonly path: string,
) {
const params = route.extract(path)
if ( !params ) {
const error = new ErrorWithContext('Cannot get params for route. Path does not match.')
error.context = {
matchedRoute: String(route),
requestPath: path,
}
throw error
}
this.params = params
2021-03-09 15:42:19 +00:00
this.preflight = route.resolvePreflight()
2021-03-08 17:08:56 +00:00
this.handler = route.resolveHandler()
2021-03-09 15:42:19 +00:00
this.postflight = route.resolvePostflight()
}
}