NestJs -Pass in path to route handler via Dynamic Module

923 views Asked by At

Im working on a team that has a bunch of services so we have a npm package that contains code shared between the services.

We have a Health check module that sets the path to globalPrefix/health. Im attempting to make this value configurable in a maintainable way.

@Injectable()
@Controller()
export class HealthController {
  private readonly healthCheckOptions: HealthConfigurationOptions; 
  private readonly url: string; 

  constructor(
    @Inject('CONFIGURATION_OPTIONS') private options: HealthConfigurationOptions,
    private readonly healthService: HealthService,
    ) {
      this.healthCheckOptions = options || {}
      this.url = options.url
    }

  @Get(this.url)
  async healthHandler(): Promise<HealthDto | TmoHttpException> {
    return this.healthService.getStatus();
  }
}

My idea was to create a Dynamic Module that can take a path as an option. In the example above There is a Dynamic Health Module that accepts an options object. But it seems like during compilation the route handler is set before the class is constructed meaning that i cannot use this.url like @Get(this.url) because there is no this yet.

At this point Im a bit stumped and haven't found anything online doing what I need.

1

There are 1 answers

0
navanjr On
Reflect.defineMetadata(PATH_METADATA, 'my_custom_path', MyController);

while registering your custom dynamic module will change the path of your controller. however there are still issues with this approach.

see here: https://github.com/nestjs/nest/issues/1438#issuecomment-1324011241