'How to make calls to services dynamic depending on parameters passed?

I have a NestJS controller similar to the one below.So depending on the parameter passed in URL, I want to redirect to correct service. The services will generally have the same functions in all with different functionality and have to be separate services. There can be multiple services (maybe even more than 10) .There is going to be only 1 controller and I want the check to be in all functions/apis in the controller so if/else checks in all will be too cumbersome.So how can I centralize it so that I can check the id parameter and call the relevant service for all api requests?

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()

}

}


Solution 1:[1]

Should just be a simple if, right?

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}`);
  }
 }

}

If you have more than 4 or so services, I'd recommend registering each service as a custom provider like so:

{
  provide: 'cnnService',
  useClass: CnnService
}

Adding this kind of custom provider for each news service you have in your NewsModule you can then inject the ModuleRef class and do return this.moduleRef.get(${id}Service).getNews() in your controller method to change between which service is used, catching errors in a filter as necessary.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1