【问题标题】:How to get the configurations from within a module import in NestJS?如何从 NestJS 的模块导入中获取配置?
【发布时间】:2019-06-15 22:13:50
【问题描述】:

假设我的模块定义如下:

@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      // Use ConfigService here
      secretOrPrivateKey: 'secretKey',
      signOptions: {
        expiresIn: 3600,
      },
    }),
    PrismaModule,
  ],
  providers: [AuthResolver, AuthService, JwtStrategy],
})
export class AuthModule {}

现在我怎样才能从这里的ConfigService 获得secretKey

【问题讨论】:

    标签: javascript node.js typescript nestjs


    【解决方案1】:

    你必须使用registerAsync,所以你可以注入你的ConfigService。有了它,您可以导入模块、注入提供程序,然后在返回配置对象的工厂函数中使用这些提供程序:

    JwtModule.registerAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        secretOrPrivateKey: configService.getString('SECRET_KEY'),
        signOptions: {
            expiresIn: 3600,
        },
      }),
      inject: [ConfigService],
    }),
    

    有关详细信息,请参阅async options docs

    【讨论】:

    • 另外,如果您已经在应用模块中全局导入了 ConfigModule,则不需要导入它。即 ConfigModule.forRoot({ isGlobal: true, expandVariables: true, }),
    • @SegunKess 这是一个非常好的提示!
    【解决方案2】:

    或者还有其他解决方案,创建一个 JwtStrategy 类,如下所示:

    @Injectable()
    export class JwtStrategy extends PassportStrategy(Strategy) {
        constructor(private readonly authService: AuthService) {
            super({
                jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
                secretOrKey: config.session.secret,
                issuer: config.uuid,
                audience: config.session.domain
            });
        }
    
        async validate(payload: JwtPayload) {
            const user = await this.authService.validateUser(payload);
            if (!user) {
                throw new UnauthorizedException();
            }
            return user;
        }
    }
    

    在那里,您可以将ConfigService 作为参数传递给构造函数,但我只使用普通文件中的配置。

    然后,不要忘记将它放在模块中的提供者数组中。

    问候。

    【讨论】:

    • 这里不能传ConfigService,因为super()中不允许使用this
    • 问? [还有 10 个]
    • 如果在构造函数中传递ConfigService,则无法在super()函数中访问。 stackoverflow.com/questions/51896505/…
    • 你为什么需要在那里访问它?
    • 我只是在回复你所说的......你正在使用静态配置文件。我只是告诉它不适用于 ConfigService,仅此而已
    猜你喜欢
    • 2020-06-30
    • 2022-12-30
    • 2020-12-01
    • 2021-11-06
    • 2021-07-15
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 2023-01-31
    相关资源
    最近更新 更多