import { Container , RouteItem , Injectable , InjectConfig } from '@tiejs/common' ; import { controllerStore } from './stores/controllerStore' ; import { actionStore } from './stores/actionStore' ; import { getClassMethodNames } from './utils/getClassMethodNames' ; import { ControllerConfig } from './interfaces/ControllerConfig' ; @ Injectable ( ) export class RouteBuilder { constructor ( @ InjectConfig ( 'controller' ) private controllerConfig ) { } buildRoutes ( ) { const routes = [ ] ; const { controllers = [ ] } = this . controllerConfig ; for ( const ControllerClass of controllers ) { const basePath = controllerStore . get ( ControllerClass ) ; let instance = Container . get < any > ( ControllerClass ) ; const prototype = Object . getPrototypeOf ( instance ) ; const methodNames = getClassMethodNames ( ControllerClass ) ; for ( const methodName of methodNames ) { const actionFn = prototype [ methodName ] ; const value = actionStore . get ( actionFn ) ; if ( ! value ) continue ; const { path , method , view , fn , target , propertyKey } = value ; routes . push ( { method , methodName , path : this . mergePath ( basePath , path ) , instance , handler : instance [ methodName ] , view , fn , target , propertyKey , } ) ; } } return routes ; } mergePath ( basePath , path ) { basePath = basePath . replace ( /^\/|\/$/ , '' ) ; if ( Array . isArray ( path ) ) { return path . map ( p => { p = p . replace ( /^\/|\/$/ , '' ) ; if ( ! basePath && ! p ) return '/' ; return `/${ basePath }/${ p }` . replace ( /\/\// , '/' ) . replace ( /\/$/ , '' ) ; } ) ; } if ( typeof path === 'string' ) { path = path . replace ( /^\/|\/$/ , '' ) ; if ( ! basePath && ! path ) return '/' ; return `/${ basePath }/${ path }` . replace ( /\/\// , '/' ) . replace ( /\/$/ , '' ) ; } throw new Error ( 'path not correct' ) ; } }