lib/src/http/routing/ActivatedRoute.ts

81 lines
2.6 KiB
TypeScript
Raw Normal View History

2021-06-03 03:36:25 +00:00
import {ErrorWithContext} from '../../util'
2022-01-19 19:24:59 +00:00
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']}
2021-03-25 13:50:13 +00:00
/**
* Class representing a resolved route that a request is mounted to.
*/
@Injectable()
2022-01-19 19:24:59 +00:00
export class ActivatedRoute<TReturn, THandlerParams extends unknown[]> {
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.
*/
2022-01-19 19:24:59 +00:00
public readonly handler: Constructable<(...x: THandlerParams) => TReturn>
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[]
2022-01-19 19:24:59 +00:00
public readonly parameters: HandlerParamProviders<THandlerParams>
public resolvedParameters?: THandlerParams
constructor(
2021-03-25 13:50:13 +00:00
/** The route this ActivatedRoute refers to. */
2022-01-19 19:24:59 +00:00
public readonly route: Route<TReturn, THandlerParams>,
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
}
2022-01-19 19:24:59 +00:00
if ( !route.handler ) {
throw new ErrorWithContext('Cannot instantiate ActivatedRoute. Matched route is not handled.', {
matchedRoute: String(route),
requestPath: path,
})
}
this.params = params
2022-01-19 19:24:59 +00:00
this.preflight = route.getPreflight().toArray()
this.handler = route.handler
this.postflight = route.getPostflight().toArray()
this.parameters = route.getParameters().toArray() as HandlerParamProviders<THandlerParams>
}
}