简体   繁体   English

NestJS:如何在另一个模块中使用 ConfigModule 值?

[英]NestJS: How to use ConfigModule values in another module?

This is how my app.module.ts of my nestJS looks like:这就是我的NestJS的 app.module.ts 的样子:

  @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.由于 GraphQLModule 参数 object 变得有点复杂,我想将其重构为配置 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?但是如何访问我在 ConfigModule envFilePath 中导入的 process.env 变量?

You should use the asynchronous registration method: forRootAsync .您应该使用异步注册方法: 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 文档中的更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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