typescript - 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;
}
}
解决方案
包括实体而不是存储库,然后您不需要导入它们
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]),
}
推荐阅读
- mysql - 在线测验考试数据库模式结构表关系使用laravel
- java - 无法从完全托管的 Google Cloud Run 发出出站请求
- microsoft-graph-api - Microsoft Graph API 帮助(graph.microsoft.com/v1.0/me/messages)
- android - Android Studio 离线选项未显示
- javascript - 输入文件点击事件不等待 chrome 上的文件选择
- c# - Windows 上 .net core 3.0 webapi 上的 Swagger 错误(无法解析“ISwaggerProvider”类型的服务)
- ktor - 如何连接到 ktor 服务器上的外部 api
- sql - Oracle合并具有多个值的列
- html - 使用 Prepros 引导本地
- python-3.x - 电子邮件不发送excel附件