Fix route CLI commands

This commit is contained in:
Garrett Mills 2022-01-20 00:54:55 -06:00
parent dc16dfdb81
commit 32050cb2ce
3 changed files with 84 additions and 24 deletions

View File

@ -2,6 +2,7 @@ import {Directive, OptionDefinition} from '../Directive'
import {Inject, Injectable} from '../../di' import {Inject, Injectable} from '../../di'
import {Routing} from '../../service/Routing' import {Routing} from '../../service/Routing'
import Table = require('cli-table') import Table = require('cli-table')
import {HTTPMethod} from '../../http/lifecycle/Request'
@Injectable() @Injectable()
export class RouteDirective extends Directive { export class RouteDirective extends Directive {
@ -32,34 +33,40 @@ export class RouteDirective extends Directive {
.toLowerCase() .toLowerCase()
.trim() .trim()
/* this.routing.getCompiled() const matched = this.routing.getCompiled()
.filter(match => match.getRoute().trim() === route && (!method || match.getMethod() === method)) .filter(match => {
.tap(matches => { if ( !method ) {
if ( !matches.length ) { return match.getRoute().trim() === route
this.error('No matching routes found. (Use `./ex routes` to list)')
process.exitCode = 1
} }
return (
(match.getRoute().trim() === route && match.getMethods().includes(method as HTTPMethod))
|| match.match(method as HTTPMethod, route)
)
}) })
.each(match => { .some(match => {
const pre = match.getPreflight() const displays = match.getDisplays()
.map<[string, string]>(ware => [ware.stage, this.handlerToString(ware.handler)]) .map<[string, string]>(ware => [ware.stage, ware.display])
const post = match.getMiddlewares() if ( displays.isEmpty() ) {
.where('stage', '=', 'post') return
.map<[string, string]>(ware => [ware.stage, this.handlerToString(ware.handler)]) }
const maxLen = match.getMiddlewares().max(ware => this.handlerToString(ware.handler).length) const maxLen = displays.max(x => x[1].length)
const table = new Table({ const table = new Table({
head: ['Stage', 'Handler'], head: ['Stage', 'Handler'],
colWidths: [10, Math.max(maxLen, match.getDisplayableHandler().length) + 2], colWidths: [10, maxLen + 2],
}) })
table.push(...pre.toArray()) displays.each(x => table.push(x))
table.push(['handler', match.getDisplayableHandler()])
table.push(...post.toArray())
this.info(`\nRoute: ${match}\n\n${table}`) this.info(`\nRoute: ${match}\n\n${table}`)
})*/ return true
})
if ( !matched ) {
this.error('No matching routes found.')
}
} }
} }

View File

@ -17,9 +17,14 @@ export class RoutesDirective extends Directive {
} }
async handle(): Promise<void> { async handle(): Promise<void> {
/* const maxRouteLength = this.routing.getCompiled().max(route => String(route).length) const compiled = this.routing.getCompiled()
const maxHandlerLength = this.routing.getCompiled().max(route => route.getDisplayableHandler().length)
const rows = this.routing.getCompiled().map<[string, string]>(route => [String(route), route.getDisplayableHandler()]) const maxRouteLength = compiled.strings().max('length')
const maxHandlerLength = compiled.mapCall('getHandlerDisplay')
.whereDefined()
.max('length')
const rows = compiled.map(route => [String(route), route.getHandlerDisplay()])
const table = new Table({ const table = new Table({
head: ['Route', 'Handler'], head: ['Route', 'Handler'],
@ -28,6 +33,6 @@ export class RoutesDirective extends Directive {
table.push(...rows.toArray()) table.push(...rows.toArray())
this.info('\n' + table)*/ this.info('\n' + table)
} }
} }

View File

@ -1,4 +1,4 @@
import {Collection, Either, ErrorWithContext, Pipeline, PrefixTypeArray, right} from '../../util' import {Collection, Either, ErrorWithContext, Maybe, Pipeline, PrefixTypeArray, right} from '../../util'
import {ResponseFactory} from '../response/ResponseFactory' import {ResponseFactory} from '../response/ResponseFactory'
import {HTTPMethod, Request} from '../lifecycle/Request' import {HTTPMethod, Request} from '../lifecycle/Request'
import {constructable, Constructable, Container, Instantiable, isInstantiableOf, TypedDependencyKey} from '../../di' import {constructable, Constructable, Container, Instantiable, isInstantiableOf, TypedDependencyKey} from '../../di'
@ -180,6 +180,8 @@ export class Route<TReturn extends ResponseObject, THandlerParams extends unknow
handler?: Constructable<(...x: THandlerParams) => TReturn> handler?: Constructable<(...x: THandlerParams) => TReturn>
protected displays: Collection<{stage: 'pre'|'post'|'handler', display: string}> = new Collection()
constructor( constructor(
protected method: HTTPMethod | HTTPMethod[], protected method: HTTPMethod | HTTPMethod[],
protected route: string, protected route: string,
@ -230,6 +232,14 @@ export class Route<TReturn extends ResponseObject, THandlerParams extends unknow
return this.parameters.clone() return this.parameters.clone()
} }
public getDisplays(): Collection<{ stage: 'pre'|'handler'|'post', display: string }> {
return this.displays.clone()
}
public getHandlerDisplay(): Maybe<string> {
return this.displays.firstWhere('stage', '=', 'handler')?.display
}
/** /**
* Returns true if this route matches the given HTTP verb and request path. * Returns true if this route matches the given HTTP verb and request path.
* @param method * @param method
@ -313,6 +323,7 @@ export class Route<TReturn extends ResponseObject, THandlerParams extends unknow
this.preflight = other.preflight.clone() this.preflight = other.preflight.clone()
this.postflight = other.postflight.clone() this.postflight = other.postflight.clone()
this.aliases = other.aliases.clone() this.aliases = other.aliases.clone()
this.displays = other.displays.clone()
} }
public calls<TKey>( public calls<TKey>(
@ -322,6 +333,11 @@ export class Route<TReturn extends ResponseObject, THandlerParams extends unknow
this.handler = constructable<TKey>(key) this.handler = constructable<TKey>(key)
.tap(inst => Function.prototype.bind.call(selector(inst), inst as any) as ((...params: THandlerParams) => TReturn)) .tap(inst => Function.prototype.bind.call(selector(inst), inst as any) as ((...params: THandlerParams) => TReturn))
this.displays.push({
stage: 'handler',
display: `${key.name}(${selector})`,
})
Route.registeredRoutes.push(this as unknown as Route<unknown, unknown[]>) // man this is stupid Route.registeredRoutes.push(this as unknown as Route<unknown, unknown[]>) // man this is stupid
return this as HandledRoute<TReturn, THandlerParams> return this as HandledRoute<TReturn, THandlerParams>
} }
@ -332,25 +348,45 @@ export class Route<TReturn extends ResponseObject, THandlerParams extends unknow
this.handler = Pipeline.id<Container>() this.handler = Pipeline.id<Container>()
.tap(() => handler) .tap(() => handler)
this.displays.push({
stage: 'handler',
display: `(closure)`,
})
Route.registeredRoutes.push(this as unknown as Route<unknown, unknown[]>) Route.registeredRoutes.push(this as unknown as Route<unknown, unknown[]>)
return this as HandledRoute<TReturn, THandlerParams> return this as HandledRoute<TReturn, THandlerParams>
} }
public pre(middleware: Instantiable<Middleware>): this { public pre(middleware: Instantiable<Middleware>): this {
this.preflight.push(request => request.make<Middleware>(middleware, request).apply()) this.preflight.push(request => request.make<Middleware>(middleware, request).apply())
this.displays.push({
stage: 'pre',
display: `${middleware.name}`,
})
return this return this
} }
public post(middleware: Instantiable<Middleware>): this { public post(middleware: Instantiable<Middleware>): this {
this.postflight.push(request => request.make<Middleware>(middleware, request).apply()) this.postflight.push(request => request.make<Middleware>(middleware, request).apply())
this.displays.push({
stage: 'pre',
display: `${middleware.name}`,
})
return this return this
} }
public input<T extends Validator<T>>(validator: ValidatorFactory<T>): Route<TReturn, PrefixTypeArray<Valid<T>, THandlerParams>> { public input<T>(validator: ValidatorFactory<T>): Route<TReturn, PrefixTypeArray<Valid<T>, THandlerParams>> {
if ( !(validator instanceof Validator) ) { if ( !(validator instanceof Validator) ) {
validator = validator() validator = validator()
} }
this.displays.push({
stage: 'pre',
display: `input(${validator.constructor.name})`,
})
return this.parameterMiddleware(validateMiddleware(validator)) return this.parameterMiddleware(validateMiddleware(validator))
} }
@ -372,6 +408,18 @@ export class Route<TReturn extends ResponseObject, THandlerParams extends unknow
return `${method.join('|')} -> ${this.route}` return `${method.join('|')} -> ${this.route}`
} }
/**
* Return a new Pipe of this collection.
*/
pipeTo<TOut>(pipeline: Pipeline<this, TOut>): TOut {
return pipeline.apply(this)
}
/** Build and apply a pipeline. */
pipe<TOut>(builder: (pipeline: Pipeline<this, this>) => Pipeline<this, TOut>): TOut {
return builder(Pipeline.id()).apply(this)
}
/** Prefix the route's path with the given prefix, normalizing `/` characters. */ /** Prefix the route's path with the given prefix, normalizing `/` characters. */
private prepend(prefix: string): this { private prepend(prefix: string): this {
if ( !prefix.endsWith('/') ) { if ( !prefix.endsWith('/') ) {