How can I pass options to my AppModule with NestJS?

Viewed 1800

I would like to use my NestJS app as a sub app that I can mount in another express app. I would like to be able to pass some options to my NestJS app. Therefore I've created a mount function like so:

import { boot } from './boot';

export async function mount(app, mountPath: string, options) {
  const subApp = await boot(options)
  await subApp.init()

  app.use(mountPath, subApp.getHttpAdapter().getInstance());

  return app
}

The boot function looks like this:

import { NestFactory } from '@nestjs/core';
import { NestApplicationOptions } from '@nestjs/common';
import { AppModule } from './app.module';

export async function boot(options) {
  return NestFactory.create(AppModule, options);
}

Question: How can I access these options in my modules? My AppModule currently looks like this:

@Module({
  imports: [
    ModuleA,
    MobuleB
  ],
})
export class AppModule {
}

Is it completely wrong to pass the options into the NestFactory? I would like to initialize my app with those options and then access them in my modules.

2 Answers

I think that the easiest, most orthodox way of doing so is by creating a configuration module that provides a configuration service. You can then initialise it however you want, and use it wherever.

You can use the following nestjs official module: https://docs.nestjs.com/techniques/configuration or either create a one of your own.

Related