@nestjs/core#ModuleRef TypeScript Examples

The following examples show how to use @nestjs/core#ModuleRef. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: read-event-bus.ts    From nestjs-geteventstore with MIT License 6 votes vote down vote up
constructor(
    @Inject(READ_EVENT_BUS_CONFIG)
    private readonly config: ReadEventBusConfigType<EventBase>,
    private readonly prepublish: EventBusPrepublishService<EventBase>,
    commandBus: CommandBus,
    moduleRef: ModuleRef,
  ) {
    super(commandBus, moduleRef);
    this.logger.debug('Registering Read EventBus for EventStore...');
  }
Example #2
Source File: write-event-bus.ts    From nestjs-geteventstore with MIT License 6 votes vote down vote up
constructor(
    @Inject(EVENT_STORE_SERVICE)
    private readonly eventstoreService: IEventStoreService,
    @Inject(WRITE_EVENT_BUS_CONFIG)
    private readonly config: IWriteEventBusConfig,
    private readonly prepublish: EventBusPrepublishService,
    commandBus: CommandBus,
    moduleRef: ModuleRef,
  ) {
    super(commandBus, moduleRef);
    this.logger.debug('Registering Write EventBus for EventStore...');
    this.publisher = new EventStorePublisher<EventBase>(
      this.eventstoreService,
      this.config,
    );
  }
Example #3
Source File: app.service.ts    From nest_transact with MIT License 6 votes vote down vote up
constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(Purse)
    private readonly purseRepository: Repository<Purse>,
    /**
     * [PurseSavingService] injected to current service
     * and all its methods will be transactional in the transaction
     * which will be initiated from the [AppController]
     */
    private readonly purseSavingService: PurseSavingService,
    moduleRef: ModuleRef,
  ) {
    super(moduleRef);
  }
Example #4
Source File: user-hook.factory.ts    From nest-casl with MIT License 6 votes vote down vote up
export async function userHookFactory(
  moduleRef: ModuleRef,
  hookOrTuple?: AnyClass<UserBeforeFilterHook> | UserBeforeFilterTuple,
): Promise<UserBeforeFilterHook> {
  if (!hookOrTuple) {
    return new NullUserHook();
  }
  if (Array.isArray(hookOrTuple)) {
    const [ServiceClass, runFunction] = hookOrTuple;
    const service = moduleRef.get(ServiceClass);
    return new TupleUserHook<typeof ServiceClass>(service, runFunction);
  }
  return moduleRef.create<UserBeforeFilterHook>(hookOrTuple);
}
Example #5
Source File: user-hook.factory.spec.ts    From nest-casl with MIT License 6 votes vote down vote up
describe('userHookFactory', () => {
  const moduleRef = {
    get: jest.fn(),
  } as unknown as ModuleRef;

  it('resolves to instance of TupleUserHook with tuple hook passed', async () => {
    expect(await userHookFactory(moduleRef, [ServiceClass, async (user) => user])).toBeInstanceOf(TupleUserHook);
  });

  it('TupleUserHook runs passed function', async () => {
    const tupleFunc = jest.fn().mockImplementation(async (user) => user);
    const tupleUserHook = await userHookFactory(moduleRef, [ServiceClass, tupleFunc]);
    tupleUserHook.run({ id: 'id', roles: [] });
    expect(tupleFunc).toBeCalled();
  });
});
Example #6
Source File: subject-hook.factory.ts    From nest-casl with MIT License 6 votes vote down vote up
export async function subjectHookFactory(
  moduleRef: ModuleRef,
  hookOrTuple?: AnyClass<SubjectBeforeFilterHook> | SubjectBeforeFilterTuple,
): Promise<SubjectBeforeFilterHook> {
  if (!hookOrTuple) {
    return new NullSubjectHook();
  }
  if (Array.isArray(hookOrTuple)) {
    const [ServiceClass, runFunction] = hookOrTuple;
    const service = moduleRef.get(ServiceClass, { strict: false });
    return new TupleSubjectHook<typeof ServiceClass>(service, runFunction);
  }
  return moduleRef.create<SubjectBeforeFilterHook>(hookOrTuple);
}
Example #7
Source File: bull.explorer.ts    From nestjs-bullmq with MIT License 5 votes vote down vote up
constructor(
    private readonly moduleRef: ModuleRef,
    private readonly discoveryService: DiscoveryService,
    private readonly metadataAccessor: BullMetadataAccessor,
    private readonly metadataScanner: MetadataScanner,
  ) {}
Example #8
Source File: puppeteer-core.module.ts    From nest-puppeteer with MIT License 5 votes vote down vote up
constructor(
    @Inject(PUPPETEER_INSTANCE_NAME) private readonly instanceName: string,
    private readonly moduleRef: ModuleRef,
  ) {}
Example #9
Source File: queue.module.ts    From nest-amqp with MIT License 5 votes vote down vote up
constructor(
    @Inject(QUEUE_MODULE_OPTIONS) private readonly moduleOptions: QueueModuleOptions,
    private readonly queueService: QueueService,
    private readonly listenerExplorer: ListenerExplorer,
    private readonly moduleRef: ModuleRef,
  ) {}
Example #10
Source File: strategy.registry.ts    From nestjs-oauth2-server-module with MIT License 5 votes vote down vote up
constructor(
        private readonly moduleRef: ModuleRef,
    ) {}
Example #11
Source File: app.service.ts    From bank-server with MIT License 5 votes vote down vote up
constructor(private readonly _moduleRef: ModuleRef) {}
Example #12
Source File: tenancy-core.module.ts    From nestjs-tenancy with MIT License 5 votes vote down vote up
constructor(
        private readonly moduleRef: ModuleRef,
    ) { }
Example #13
Source File: mikro-orm-core.module.ts    From nestjs with MIT License 5 votes vote down vote up
constructor(@Inject(MIKRO_ORM_MODULE_OPTIONS)
              private readonly options: MikroOrmModuleOptions,
              private readonly moduleRef: ModuleRef) { }
Example #14
Source File: access.guard.ts    From nest-casl with MIT License 5 votes vote down vote up
constructor(
    private reflector: Reflector,
    private readonly accessService: AccessService,
    private moduleRef: ModuleRef,
  ) {}
Example #15
Source File: prepare-options.service.ts    From typegraphql-nestjs with MIT License 5 votes vote down vote up
constructor(
    private readonly moduleRef: ModuleRef,
    private readonly modulesContainer: ModulesContainer,
  ) {}
Example #16
Source File: with-transaction.ts    From nest_transact with MIT License 5 votes vote down vote up
constructor(private moduleRef: ModuleRef) {
  }
Example #17
Source File: with-transaction.ts    From nest_transact with MIT License 5 votes vote down vote up
private getArgument(param: string | ClassType | ForwardRef, manager: EntityManager, excluded: ClassType[]): any {
    if (typeof param === 'object' && 'forwardRef' in param) {
      return this.moduleRef.get(param.forwardRef().name, { strict: false });
    }
    const id = typeof param === 'string' ? param : typeof param === 'function' ? param.name : undefined;
    if (id === undefined) {
      throw new Error(`Can't get injection token from ${param}`);
    }
    const isExcluded = excluded.length > 0 && excluded.some((ex) => ex.name === id);
    if (id === `${ModuleRef.name}`) {
      return this.moduleRef;
    }
    if (isExcluded) {
      /// Returns current instance of service, if it is excluded
      return this.moduleRef.get(id, { strict: false });
    }
    let argument: Repository<any>;
    if (this.cache.has(id)) {
      return this.cache.get(id);
    }
    const canBeRepository = id.includes('Repository');
    if (typeof param === 'string' || canBeRepository) {
      // Fetch the dependency
      let dependency: Repository<any>;
      try {
        if (canBeRepository) {
          // Return directly if param is custom repository.
          return manager.getCustomRepository(param as any);
        }
      } catch (error) {
        dependency = this.moduleRef.get(param, { strict: false });
      }
      if (dependency! instanceof Repository || canBeRepository) {
        // If the dependency is a repository, make a new repository with the desired transaction manager.
        const entity: any = dependency!.metadata.target;
        argument = manager.getRepository(entity);
      } else {
        // The dependency is not a repository, use it directly.
        argument = dependency!;
      }
    } else {
      argument = this.findArgumentsForProvider(param as ClassType, manager, excluded);
    }
    this.cache.set(id, argument);
    return argument;
  }
Example #18
Source File: purse-saving.service.ts    From nest_transact with MIT License 5 votes vote down vote up
constructor(
    @InjectRepository(Purse)
    private readonly purseRepository: Repository<Purse>,
    moduleRef: ModuleRef,
  ) {
    super(moduleRef);
  }
Example #19
Source File: with-transaction.d.ts    From nest_transact with MIT License 5 votes vote down vote up
constructor(moduleRef: ModuleRef);
Example #20
Source File: DesktopAPI.ts    From rewind with MIT License 5 votes vote down vote up
/**
 * The usual bootstrap happens with the concrete knowledge of the osu! folder. Only at the first start up of the
 * application we will have to refer to boot differently.
 */
async function normalBootstrap(settings: {
  osuFolder: string;
  songsFolder: string;
  userDataPath: string;
  appResourcesPath: string;
  logDirectory: string;
}) {
  const { osuFolder, userDataPath, appResourcesPath, logDirectory, songsFolder } = settings;
  // Find out osu! folder through settings
  const rewindCfgPath = getRewindCfgPath(userDataPath);
  const skinNameResolverConfig: SkinNameResolverConfig = [
    { prefix: "osu", path: join(osuFolder, "Skins") },
    { prefix: "rewind", path: join(appResourcesPath, "Skins") },
  ];

  @Module({
    imports: [EventEmitterModule.forRoot()],
    controllers: [
      LocalReplayController,
      SkinController,
      LocalBlueprintController,
      NormalStatusController,
      DesktopConfigController,
    ],
    providers: [
      { provide: OSU_FOLDER, useValue: osuFolder },
      { provide: OSU_SONGS_FOLDER, useValue: songsFolder },
      { provide: REWIND_CFG_PATH, useValue: rewindCfgPath },
      { provide: SKIN_NAME_RESOLVER_CONFIG, useValue: skinNameResolverConfig },
      SkinNameResolver,
      SkinService,
      EventsGateway,
      ReplayWatcher,
      LocalReplayService,
      LocalBlueprintService,
      OsuDBDao,
      DesktopConfigService,
    ],
  })
  class RewindDesktopModule implements OnModuleInit {
    constructor(private moduleRef: ModuleRef) {}

    async onModuleInit(): Promise<void> {
      const [osuFolder, replayWatcher, localBlueprintService] = await Promise.all([
        this.moduleRef.resolve(OSU_FOLDER),
        this.moduleRef.resolve(ReplayWatcher),
        this.moduleRef.resolve(LocalBlueprintService),
      ]);

      const replaysFolder = join(osuFolder, "Replays");
      replayWatcher.watchForReplays(replaysFolder);

      localBlueprintService
        .getAllBlueprints()
        .then((blueprints) => Logger.log(`Loaded all ${Object.keys(blueprints).length} blueprints.`));
      // TODO: Emit and then set the status to booted
      Logger.log(`RewindDesktopModule onModuleInit finished with settings: ${JSON.stringify(settings)}`);
    }
  }

  const app = await NestFactory.create<NestExpressApplication>(RewindDesktopModule, {
    logger: createLogger(logDirectory),
  });

  app.setGlobalPrefix(globalPrefix);
  app.enableCors();

  // So that "rewind" skins are also accessible
  skinNameResolverConfig.forEach((config) => {
    app.useStaticAssets(config.path, { prefix: `/static/skins/${config.prefix}` });
  });
  app.useStaticAssets(songsFolder, { prefix: "/static/songs" });
  // app.useLogger();

  await app.listen(port, listenCallback);
}
Example #21
Source File: event-bus-prepublish.service.ts    From nestjs-geteventstore with MIT License 5 votes vote down vote up
constructor(private readonly moduleRef: ModuleRef) {}