You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lib/src/http/routing/ActivatedRoute.ts

81 lines
2.6 KiB

import {ErrorWithContext} from '../../util'
import {ParameterProvidingMiddleware, ResolvedRouteHandler, Route} from './Route'
import {Constructable, Injectable} from '../../di'
export type HandlerParamProviders<THandlerParams extends unknown[]> = {
[Index in keyof THandlerParams]: ParameterProvidingMiddleware<THandlerParams[Index]>
} & {length: THandlerParams['length']}
/**
* Class representing a resolved route that a request is mounted to.
*/
@Injectable()
export class ActivatedRoute<TReturn, THandlerParams extends unknown[]> {
/**
* 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}
/**
* The resolved function that should handle the request for this route.
*/
public readonly handler: Constructable<(...x: THandlerParams) => TReturn>
/**
* Pre-middleware that should be applied to the request on this route.
*/
public readonly preflight: ResolvedRouteHandler[]
/**
* Post-middleware that should be applied to the request on this route.
*/
public readonly postflight: ResolvedRouteHandler[]
public readonly parameters: HandlerParamProviders<THandlerParams>
public resolvedParameters?: THandlerParams
constructor(
/** The route this ActivatedRoute refers to. */
public readonly route: Route<TReturn, THandlerParams>,
/** The request path that activated that route. */
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
}
if ( !route.handler ) {
throw new ErrorWithContext('Cannot instantiate ActivatedRoute. Matched route is not handled.', {
matchedRoute: String(route),
requestPath: path,
})
}
this.params = params
this.preflight = route.getPreflight().toArray()
this.handler = route.handler
this.postflight = route.getPostflight().toArray()
this.parameters = route.getParameters().toArray() as HandlerParamProviders<THandlerParams>
}
}