Thu, 07/01/2021 - 07:41
Curently NestJS does not provide method for dynamic routes. The routes of controllers must be defined using the decorators @Controller(path)
, @Get(path)
etc. However there is a quick solution that get the job done.
1. Define factory that return the Controller class like below
// mymodule.controller.ts
export function getControllerClass({ customPath }): Type<any> {
@Controller()
class MyController {
constructor(private service: MyService) { }
@Get([dynamicPath])
async getSomething(@Res() res: Response) {
//...
}
}
return MyController
}
2. Configure controller routes via your module
// mymodule.module.ts
@Module({})
export class MyModule {
static forRoot(config): DynamicModule {
const { customPath } = config.customPath;
const MyController = getControllerClass({ customPath })
return {
module: MyModule,
providers: [
MyService
],
exports: [MyService],
controllers: [MyController]
};
}
}
Authored by
Tags