import {Collection, ErrorWithContext} from "@extollo/util" import {AppClass} from "../../lifecycle/AppClass" import {RouteHandler} from "./Route" import {Container} from "@extollo/di" import {Logging} from "../../service/Logging"; export class RouteGroup extends AppClass { private static currentGroupNesting: RouteGroup[] = [] protected static namedGroups: {[key: string]: () => void } = {} protected middlewares: Collection<{ stage: 'pre' | 'post', handler: RouteHandler }> = new Collection<{stage: "pre" | "post"; handler: RouteHandler}>() public static getCurrentGroupHierarchy(): RouteGroup[] { return [...this.currentGroupNesting] } public static named(name: string, define: () => void) { if ( this.namedGroups[name] ) { Container.getContainer() .make(Logging) .warn(`Replacing named route group: ${name}`) } this.namedGroups[name] = define } public static include(name: string) { if (!this.namedGroups[name]) { throw new ErrorWithContext(`No route group exists with name: ${name}`, {name}) } this.namedGroups[name]() } constructor( public readonly group: () => void | Promise, public readonly prefix: string ) { super() } pre(middleware: RouteHandler) { this.middlewares.push({ stage: 'pre', handler: middleware }) return this } post(middleware: RouteHandler) { this.middlewares.push({ stage: 'post', handler: middleware, }) return this } getGroupMiddlewareDefinitions() { return this.middlewares } }