import { coreErrorFactory } from '@marblejs/core' ; import { insertIf } from '@marblejs/core/dist/+internal/utils' ; import { HttpMiddlewareEffect } from '../effects/http.effects.interface' ; import { isRouteEffectGroup } from './http.router.helpers' ; import { Routing , RoutingMethod , RoutingItem , RouteEffect , RouteEffectGroup , } from './http.router.interface' ; import { factorizeRegExpWithParams } from './http.router.params.factory' ; import { notFound$ } from './http.router.effects' ; const canOverrideRoute = ( route ) => route . meta ?. overridable === true ; export const factorizeRouting = ( routes , middlewares = [ ] , parentPath = '' ) : Routing => { const routing = [ ] ; routes . forEach ( route => { const concatenatedPath = parentPath + '/' + route . path ; if ( isRouteEffectGroup ( route ) ) { return routing . push ( ... factorizeRouting ( route . effects , [ ... middlewares , ... route . middlewares ] , concatenatedPath ) ) ; } const { regExp , parameters , path } = factorizeRegExpWithParams ( concatenatedPath ) ; const foundRoute = routing . find ( route => route . regExp . source === regExp . source ) ; const method = { parameters , effect : route . effect , meta : route . meta , middlewares : [ ... middlewares , ... insertIf ( ! ! route . middleware ) ( route . middleware ) , ] , } ; if ( foundRoute ) { if ( ! canOverrideRoute ( route ) && foundRoute . methods [ route . method ] ) { const routePath = ( parentPath + route . path ) . replace ( /\/\//g , '/' ) ; throw coreErrorFactory ( `Redefinition of route at "${ route . method }: ${ routePath }"` , { contextMethod : 'factorizeRouting' , offset : 1 , printStacktrace : false } ) ; } if ( canOverrideRoute ( route ) && foundRoute . methods [ route . method ] ) { return ; } return foundRoute . methods [ route . method ] = method ; } return routing . push ( { path , regExp , methods : { [ route . method ] : method } , } as RoutingItem ) ; } ) ; return routing ; } ; export const factorizeRoutingWithDefaults = ( routes , middlewares = [ ] ) : Routing => factorizeRouting ( [ ... routes , notFound$ ] , middlewares ) ;