Add ability to pass arguments to parameter providing middleware

This commit is contained in:
Garrett Mills 2022-04-05 10:25:07 -05:00
parent 8b9f393405
commit ee21811771
3 changed files with 9 additions and 8 deletions

View File

@ -1,6 +1,6 @@
{
"name": "@extollo/lib",
"version": "0.9.24",
"version": "0.9.25",
"description": "The framework library that lifts up your code.",
"main": "lib/index.js",
"types": "lib/index.d.ts",

View File

@ -2,7 +2,7 @@ import {Request} from '../lifecycle/Request'
import {ResponseObject} from './Route'
import {Container} from '../../di'
import {CanonicalItemClass} from '../../support/CanonicalReceiver'
import {Awaitable, Either, Left, left, Right, right} from '../../util'
import {Awaitable, Either, ErrorWithContext, Left, left, Right, right} from '../../util'
/**
* Base class representing a middleware handler that can be applied to routes.
@ -37,12 +37,12 @@ export abstract class Middleware extends CanonicalItemClass {
* A type of Middleware that produces a parameter that is passed to later handlers.
* Can be used to do common look-ups, &c before routes.
*/
export abstract class ParameterMiddleware<T> extends Middleware {
export abstract class ParameterMiddleware<T, THandlerArgs extends any[] = []> extends Middleware {
/** Look up the value. */
public abstract handle(): Awaitable<Either<ResponseObject, T>>
public abstract handle(...options: THandlerArgs): Awaitable<Either<ResponseObject, T>>
apply(): ResponseObject {
return this.handle()
throw new ErrorWithContext('Attempted to apply parameter-providing middleware directly. Try using `parameterMiddleware()` instead.')
}
/** Alias for an error response return. */

View File

@ -310,8 +310,9 @@ export class Route<TReturn extends ResponseObject, THandlerParams extends unknow
return params
}
public parameterMiddleware<T>(
handler: ParameterProvidingMiddleware<T> | Instantiable<ParameterMiddleware<T>>,
public parameterMiddleware<T, THandlerArgs extends any[] = []>(
handler: ParameterProvidingMiddleware<T> | Instantiable<ParameterMiddleware<T, THandlerArgs>>,
...handlerArgs: THandlerArgs
): Route<TReturn, PrefixTypeArray<T, THandlerParams>> {
const route = new Route<TReturn, PrefixTypeArray<T, THandlerParams>>(
this.method,
@ -321,7 +322,7 @@ export class Route<TReturn extends ResponseObject, THandlerParams extends unknow
route.copyFrom(this)
if ( handler.prototype instanceof ParameterMiddleware ) {
route.parameters.push(req => req.make<ParameterMiddleware<T>>(handler).handle())
route.parameters.push(req => req.make<ParameterMiddleware<T, THandlerArgs>>(handler).handle(...handlerArgs))
}
route.parameters.push(handler as ParameterProvidingMiddleware<T>)