简体   繁体   中英

NestJS: How to use ConfigModule values in another module?

This is how my app.module.ts of my nestJS looks like:

  @Module({
    imports: [
      ConfigModule.forRoot({ envFilePath: root + '.env' }),
      GraphQLModule.forRoot<ApolloDriverConfig>({
        driver: ApolloDriver,
        cors: {
          credentials: true,
          origin: process.env.ORIGIN // <--
        }
      })
    ],
    controllers: [AppController]
  })

As the GraphQLModule parameter object gets a bit more complex, I would like to refactor it to a config function.

export default () => ({
  driver: ApolloDriver,
  cors: {
    credentials: true,
    origin: process.env.ORIGIN // <--
  }
});

@Module({
    imports: [
      ConfigModule.forRoot({ envFilePath: root + '.env' }),
      GraphQLModule.forRoot<ApolloDriverConfig>(graphQLConfig)
    ],
    controllers: [AppController]
})

But how do I get access to the process.env variables which I imported within the ConfigModule envFilePath?

You should use the asynchronous registration method: forRootAsync . Something like:

  @Module({
    imports: [
      ConfigModule.forRoot({ envFilePath: root + '.env' }),
      GraphQLModule.forRootAsync<ApolloDriverConfig>({
        driver: ApolloDriver,
        inject: [ConfigService],
        useFactory: (config: ConfigService) => ({
          cors: {
            credentials: true,
            origin: config.get('ORIGIN')
          }
        })
      })
    ],
    controllers: [AppController]
  })

More details in the docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM