Grapeoff
@Grapeoff
В чём концепция...?

Почему сервис не может получить зависимости глобального модуля?

Так как глобально зарегистрированный Guard требует внутри себя Reflector, JwtServiceи ConfigService, было принято решение сделать глобальный модуль, который импортирует в себя вышеуказанные зависимости.

@Global()
@Module({
    imports: [
        ConfigModule.forRoot({
            isGlobal: true,
            cache: true,
            envFilePath: '.env',
            validationSchema: Joi.object({
                PORT: Joi.number().required(),
                POSTGRES_PORT: Joi.number().required(),
                POSTGRES_USERNAME: Joi.string().required(),
                POSTGRES_PASSWORD: Joi.string().required(),
                POSTGRES_DATABASE: Joi.string().required(),
                SYNCHRONIZE: Joi.string().valid('YES', 'NO'),
                APOLLO_ENABLE_DEBUG_MODE: Joi.string().valid('YES', 'NO'),
                APOLLO_ENABLE_PLAYGROUND: Joi.string().valid('YES', 'NO'),
                CORS_ALLOWED_ORIGINS: Joi.string(),
                SMTP_PROTOCOL: Joi.string().required(),
                SMTP_HOST: Joi.string().required(),
                SMTP_PORT: Joi.number().required(),
                SMTP_USERNAME: Joi.string().required(),
                SMTP_PASSWORD: Joi.string().required(),
            }),
        }),
        JwtModule.registerAsync({
            imports: [ConfigModule],
            inject: [ConfigService],
            useFactory(configService: ConfigService): JwtModuleOptions {
                return {
                    signOptions: {
                        algorithm: 'HS256',
                        issuer: configService.get('JWT_ISSUER'),
                    },
                };
            },
        }),
        Reflector,
    ],
})
export class CommonModule {}

А затем он импортируется в AppModule:

@Module({
    imports: [
        CommonModule,
        ...
    ],
    controllers: [],
    providers: [{ provide: APP_GUARD, useClass: AuthGuard }],
})
export class AppModule {}

Помимо Guard, я использую JwtService в JwtFactoryService, который используется для генерации токенов при аутентификации. Так как JwtModule уже зарегистрирован глобально, я не импортирую его в AuthModule, но, почему-то зависимости из CommonModule не переходят к AuthModule.

Potential solutions:
- If JwtService is a provider, is it part of the current AuthModule?
- If JwtService is exported from a separate @Module, is that module imported within AuthModule?
  @Module({
    imports: [ /* the Module containing JwtService */ ]
  })

Error: Nest can't resolve dependencies of the JwtFactoryService (?, ConfigService). Please make sure that the argument JwtService at index [0] is available in the AuthModule context.
  • Вопрос задан
  • 231 просмотр
Решения вопроса 1
Grapeoff
@Grapeoff Автор вопроса
В чём концепция...?
Добавил все сервисы импортируемых в CommonModule модулей в секцию providers, а затем и в exports. Не знаю, костыль это или нет, но оно работает.

@Global()
@Module({
    imports: [
        ConfigModule.forRoot({}),
        JwtModule.registerAsync({})
        Reflector,
    ],
    providers: [ConfigService, JwtService, Reflector],
    exports: [ConfigService, JwtService, Reflector],
})
export class CommonModule {}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы