Home > OS >  Is it possible to Inject the NestJS app created in main.ts into a module service?
Is it possible to Inject the NestJS app created in main.ts into a module service?

Time:12-28

Assuming you have the basic NestJS setup:

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.enableCors(corsOptions);

  app.useGlobalPipes(
    new ValidationPipe({
      validateCustomDecorators: true,
      transform: true,
      whitelist: true,
      exceptionFactory: exceptionFactory,
    }),
  );
  app.useGlobalFilters(new CustomExceptionsFilter());

  const port = parseInt(process.env.PORT);
  await app.listen(port);
}

Can I access the app variable created with NestFactory from a service in a different module?

@Injectable()
export class TestService {
  constructor(
    ...
  ) {}

  async useApp(): Promise<any> {
    const app = ... // use Injected app instance created from AppModule
  }

I've tried importing AppModule and creating a NestFactory again, but it just resolves into redundancies.

CodePudding user response:

There is no way to get the app instance itself from the Nest containers, you could simply export the app once it is created by NestFactory.create().

However, if you're looking for the instance of AppModule, this bellow snippet might help you.

const app = await NestFactory.createApplicationContext(AppModule);

CodePudding user response:

NestFactory.create will create the app, which depends on modules & their providers. Using app before it has been created does not make sense.


Instead, you could tell us what you're trying to do with that app at TestService.

  • Related