如何根据传递的参数动态调用服务



我有一个类似于下面的NestJS控制器。因此,根据URL中传递的参数,我希望重定向到正确的服务。这些服务通常具有相同的功能,但具有不同的功能,并且必须是单独的服务。可以有多个服务(甚至可能超过10个(。将只有一个控制器,我希望检查控制器中的所有功能/api,所以if/else检查所有功能将太麻烦。那么,我如何集中它,以便检查id参数并为所有api请求调用相关服务呢?

class Controller {
contructor(private readonly cnnService:CnnService,private readonly bbcService:BbcService)
@Get(':id') 
getNewsData() {
// if id is cnn then 
return this.cnnService.getNews()
// else if id is bbc then
return this.bbcService.getNews()
}
}

应该只是一个简单的if,对吧?

class Controller {
contructor(private readonly cnnService:CnnService,private readonly bbcService:BbcService)
@Get(':id') 
getNewsData(@Param() { id }: {id: string}) {
if ( id === 'cnn') {
return this.cnnService.getNews()
} else if (id === 'bcc') {
return this.bbcService.getNews()
} else {
throw new BadRequestException(`Unknown News outlet ${id}`);
}
}
}

如果您有4个以上的服务,我建议将每个服务注册为自定义提供商,如下所示:

{
provide: 'cnnService',
useClass: CnnService
}

NewsModule中的每个新闻服务添加这种自定义提供程序,然后可以注入ModuleRef类,并在控制器方法中执行return this.moduleRef.get(${id}Service).getNews(),以在使用哪个服务之间进行更改,根据需要在过滤器中捕获错误。

最新更新