import {ErrorWithContext} from '../../util' import {ParameterProvidingMiddleware, ResolvedRouteHandler, Route} from './Route' import {Constructable, Injectable} from '../../di' export type HandlerParamProviders = { [Index in keyof THandlerParams]: ParameterProvidingMiddleware } & {length: THandlerParams['length']} /** * Class representing a resolved route that a request is mounted to. */ @Injectable() export class ActivatedRoute { /** * 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 public resolvedParameters?: THandlerParams constructor( /** The route this ActivatedRoute refers to. */ public readonly route: Route, /** 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 } }