nestjs无法解析依赖项,动态模块导入动态模块

时间:2020-04-15 04:03:34

标签: nestjs

以下是我的代码,JWTAuthModule是一个动态模块,我通过静态函数JWTAuthModule.forRootAsync传入了jwt选项,但是JwtModule.registerAsync无法解析JWT_AUTH_MODULE_OPTIONS。我尝试将JwtModule移到forRootAsync内,但仍然无法正常工作。如何将JWT_AUTH_MODULE_OPTIONS注入JwtModule中?谢谢!

import { JwtModule } from '@nestjs/jwt';
import { JWTStrategy } from './jwt.strategy';
import { JWTAuthService } from './jwt-auth.service';
import { JWTAuthOptions } from './jwt-auth.options';
import { JWT_AUTH_MODULE_OPTIONS } from './jwt-auth.constants';
import { ModuleMetadata, Provider } from '@nestjs/common/interfaces';
import { Module, DynamicModule, Type } from '@nestjs/common';

export interface JWTAuthModuleOptionsFactory {
  createJWTAuthModuleOptions(): Promise<JWTAuthOptions> | JWTAuthOptions;
}

export interface JWTAuthModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'>  {
  useClass?: Type<JWTAuthModuleOptionsFactory>,
  useExisting?: Type<JWTAuthModuleOptionsFactory>,
  useFactory?: (...args: Array<any>) => Promise<JWTAuthOptions> | JWTAuthOptions;
  inject?: Array<any>;
}

@Module({
  imports: [
    JwtModule.registerAsync({
      inject: [JWT_AUTH_MODULE_OPTIONS],                // <-- error here, can't resolve dependencies
      useFactory: (options: JWTAuthOptions) => {
        return {
          secret: options.secret,
          signOptions: options.signOptions,
        };
      },
    }),
  ],
  exports: [
    JWTAuthService,
  ],
  providers: [
    JWTStrategy,
    JWTAuthService,
  ],
})
export class JWTAuthModule {

  public static forRoot(options: JWTAuthOptions): DynamicModule {
    options = options ?? {};
    return {
      module: JWTAuthModule,
      providers: [
        {
          provide: JWT_AUTH_MODULE_OPTIONS,
          useValue: options,
        },
      ],
    };
  }

  public static forRootAsync(asyncOptions: JWTAuthModuleAsyncOptions): DynamicModule {
    asyncOptions = asyncOptions ?? {};
    asyncOptions.inject || (asyncOptions.inject = []);
    asyncOptions.imports || (asyncOptions.imports = []);
    return {
      module: JWTAuthModule,
      imports: [...asyncOptions.imports],
      exports: [JwtModule],
      providers: [JWTAuthModule.createAsyncOptionsProvider(asyncOptions)],
    };
  }

  private static createAsyncOptionsProvider(options: JWTAuthModuleAsyncOptions): Provider {
    if(options.useFactory) {
      return {
        inject: options.inject ?? [],
        provide: JWT_AUTH_MODULE_OPTIONS,
        useFactory: options.useFactory,
      };
    }
    return {
      inject: [options.useExisting ?? options.useClass],
      provide: JWT_AUTH_MODULE_OPTIONS,
      useFactory: async (optionsFactory: JWTAuthModuleOptionsFactory) => await optionsFactory.createJWTAuthModuleOptions(),
    };
  }

}

更新。

我没有停止尝试,创建了JWTAuthOptionsModule,并且JWTAuthModule和JwtModule导入了该选项模块,但是我必须导入两次,并且代码执行两次,是否有更好的解决方案?

import { JwtModule } from '@nestjs/jwt';
import { JWTStrategy } from './jwt.strategy';
import { JWTAuthService } from './jwt-auth.service';
import { JWTAuthOptions } from './jwt-auth.options';
import { JWT_AUTH_MODULE_OPTIONS } from './jwt-auth.constants';
import { ModuleMetadata, Provider } from '@nestjs/common/interfaces';
import { Module, DynamicModule, Type } from '@nestjs/common';

export interface JWTAuthModuleOptionsFactory {
  createJWTAuthModuleOptions(): Promise<JWTAuthOptions> | JWTAuthOptions;
}

export interface JWTAuthModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'>  {
  useClass?: Type<JWTAuthModuleOptionsFactory>,
  useExisting?: Type<JWTAuthModuleOptionsFactory>,
  useFactory?: (...args: Array<any>) => Promise<JWTAuthOptions> | JWTAuthOptions;
  inject?: Array<any>;
}

@Module({ })
class JWTAuthOptionsModule {

  public static forRootAsync(asyncOptions: JWTAuthModuleAsyncOptions): DynamicModule {
    asyncOptions = asyncOptions ?? {};
    asyncOptions.inject || (asyncOptions.inject = []);
    asyncOptions.imports || (asyncOptions.imports = []);
    const optionsProvider = JWTAuthOptionsModule.createAsyncOptionsProvider(asyncOptions);
    return {
      module: JWTAuthModule,
      imports: [...asyncOptions.imports],
      exports: [optionsProvider],
      providers: [optionsProvider],
    };
  }

  private static createAsyncOptionsProvider(options: JWTAuthModuleAsyncOptions): Provider {
    if(options.useFactory) {
      return {
        inject: options.inject ?? [],
        provide: JWT_AUTH_MODULE_OPTIONS,
        useFactory: options.useFactory,
      };
    }
    return {
      inject: [options.useExisting ?? options.useClass],
      provide: JWT_AUTH_MODULE_OPTIONS,
      useFactory: async (optionsFactory: JWTAuthModuleOptionsFactory) => await optionsFactory.createJWTAuthModuleOptions(),
    };
  }

}

@Module({
  imports: [

  ],
  exports: [
    JWTAuthService,
  ],
  providers: [
    JWTStrategy,
    JWTAuthService,
  ],
})
export class JWTAuthModule {

  public static forRootAsync(asyncOptions: JWTAuthModuleAsyncOptions): DynamicModule {
    asyncOptions = asyncOptions ?? {};
    asyncOptions.inject || (asyncOptions.inject = []);
    asyncOptions.imports || (asyncOptions.imports = []);
    return {
      module: JWTAuthModule,
      imports: [
        ...asyncOptions.imports,
        JWTAuthOptionsModule.forRootAsync(asyncOptions),    // <-- import 
        JwtModule.registerAsync({
          imports: [JWTAuthOptionsModule.forRootAsync(asyncOptions)], // <-- must import again
          inject: [JWT_AUTH_MODULE_OPTIONS],
          useFactory: (options: JWTAuthOptions) => {
            return {
              secret: options.secret,
              signOptions: options.signOptions,
            };
          },
        }),
      ],
    };
  }

}

0 个答案:

没有答案