首页 > 解决方案 > Nestjs sequelize 注入多个存储库

问题描述

我是 Nestjs 和打字稿的新手,我想知道如何简化下面的代码?正如您在下面的代码中看到的那样,它会将多个 REPOSITORY 插入到 中users.module.ts,并注入到承包商中users.services.ts

users.module.ts

import {USER_REPOSITORY, USERSTORE_REPOSITORY, STORE_REPOSITORY} from '../constants';
@Module({
  controllers: [UsersController],
  providers: [UsersService, [
  {
    provide: USER_REPOSITORY,
    useValue: Users,
  },
  {
    provide: USERSTORE_REPOSITORY,
    useValue: UserStores,
  },
  {
    provide: STORE_REPOSITORY,
    useValue: Stores,
  }
 ],
  exports: [UsersService],
})

users.services.ts

import {
  USERSTORE_REPOSITORY,
  USER_REPOSITORY,
  STORE_REPOSITORY,
} from 'src/core/constants';
export class UsersService {
   constructor(
      @Inject(USER_REPOSITORY) private readonly userRepository: typeof Users,
      @Inject(USERSTORE_REPOSITORY)
      private readonly userStoresRepository: typeof UserStores,
      @Inject(STORE_REPOSITORY) private readonly StoresRepository: typeof Stores,
    )

   async getAllUsers(): Promise<Users[]> {
      const result = await this.userRepository.findAll<Users>({
         include: [
            { model: this.userStoresRepository, include: [this.StoresRepository] },
         ]
      });
      return result;
   }
}

如果我要注入多个表,我觉得我正在创建重复代码。有没有简化的方法来做到这一点?或者是否可以让它像const userRepository = new xxxx我在函数中需要它时一样,而不是一直在承包商中注入?例如:

//users.services.ts
  export class UsersService {
     constructor()
      async getAllUsers(): Promise<Users[]> {
         const userRepository = new xxxx
         const userStoresRepository = new xxx
         const storesRepository = new xxxx
         const result = await userRepository.findAll<Users>({
            include: [
               { model: userStoresRepository, include: [storesRepository] },
            ]
         });
         return result;
      }
  }

标签: typescriptnestjssequelize-typescript

解决方案


包括实体而不是存储库,然后您不需要导入它们

export class UsersService {
     constructor()
      async getAllUsers(): Promise<Users[]> {
         const result = await userRepository.findAll<Users>({
            include: [
               { model: userStoresRepository, include: [Stores] },
            ]
         });
         return result;
      }
  }

您可以通过使用存储库模式再次简化应用程序中的一致数据访问,在这里您将定义您的包含在您的提供程序中,它将从您的服务中抽象出来。如果您遵循 OOP/领域驱动设计原则并希望在类级别而不是在服务中定义业务逻辑,这将非常有用。

export class UsersService {
     constructor()
      async getAllUsers(): Promise<Users[]> {
         const result = await userRepository.findAll<Users>();
      }
  }

import {USER_REPOSITORY, USERSTORE_REPOSITORY, STORE_REPOSITORY} from '../constants';
@Module({
  controllers: [UsersController],
  providers: [UsersService, [
  {
    provide: USER_REPOSITORY,
    useFactory: () =>
      new SequelizeRepo<User>(UserRoleAssignment, [Stores]),
}

推荐阅读