import {Singleton, Inject} from "@extollo/di" import {UniversalPath, Collection} from "@extollo/util" import {Unit} from "../lifecycle/Unit" import {Logging} from "./Logging" import {Route} from "../http/routing/Route"; import {HTTPMethod} from "../http/lifecycle/Request"; @Singleton() export class Routing extends Unit { @Inject() protected readonly logging!: Logging protected compiledRoutes: Collection = new Collection() public async up() { for await ( const entry of this.path.walk() ) { if ( !entry.endsWith('.routes.js') ) { this.logging.debug(`Skipping routes file with invalid suffix: ${entry}`) continue } this.logging.info(`Importing routes from: ${entry}`) await import(entry) } this.logging.info('Compiling routes...') this.compiledRoutes = new Collection(await Route.compile()) this.logging.info(`Compiled ${this.compiledRoutes.length} route(s).`) this.compiledRoutes.each(route => { this.logging.verbose(`${route}`) }) } public match(method: HTTPMethod, path: string): Route | undefined { return this.compiledRoutes.firstWhere(route => { return route.match(method, path) }) } public get path(): UniversalPath { return this.app().appPath('http', 'routes') } }