简体   繁体   中英

How to get the configurations from within a module import in NestJS?

Let's say I have my module defined as below:

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

Now how can I get the secretKey from the ConfigService in here?

You have to use registerAsync , so you can inject your ConfigService . With it, you can import modules, inject providers and then use those providers in a factory function that returns the configuration object:

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

For more information, see the async options docs .

Or there is another solution, create an JwtStrategy class, something like this:

@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;
    }
}

There you are able to pass ConfigService as a parameter to the constructor, but I'm using config just from plain file.

Then, don't forget to place it in array of providers in module.

Regards.

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