Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
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()

}

}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda