我必须将服务分为命令和查询。某些命令方法需要查询中的方法。我在命令的构造函数中初始化了查询变量。这是我的 Nestjs 应用程序中的示例:
//command.ts
constructor(
//...imports repos
private salonServicesQuery: SalonServicesQuery //this one IMPORTED and be used later
) {
//
}
async updateService(serviceId: number, salonId: number, dto: UpdateServiceDto) {
// do some cheking
const service = await this.salonServicesQuery.getById(serviceId, salonId);// THIS one used to retrieve methods from the query class
let category: any;
if (dto.categoryId) {
category = await this.categoryRepository.findOne({
where: { id: dto.categoryId, salon: { id: salonId } },
});
if (!category) {
throw new NotFoundException(
`Category with ID '${dto.categoryId}' not found in salon '${salonId}'`
);
}
}
// continue doing logical things
}
我的问题是:我将它们分开是否正确?有没有更有意义/更好的方法/方法?
我在命令类中导入了查询类。我没有运行程序 bc 我仍然有 env 错误,但 vsc 将其标记为绿色并且没有错误
我的问题是:我将它们分开是否正确?
“这取决于”。
如果
service
和 category
是共享相同信息的两个不同对象,那么您可能不会比仅使用单个对象更好地进行未来的理解和维护。
如果信息不同,那么可能没问题; 很常见,我们需要一些超出提供给我们作为输入的信息来完成有用的工作;在处理命令时,访问参考数据的未锁定只读副本是完全合理的事情,并使用某种外观风格来隐藏如何完成此操作的细节,从而使命令处理程序免受将来对这些实现细节的更改的影响。
试金石:考虑与 updateService 处理同时发生的沙龙服务数据被更改的情况——这样可以吗?如果答案是肯定的,那么您可以在心里将
service
数据视为“只是另一个输入”
async updateService(serviceId: number, salonId: number, dto: UpdateServiceDto) {
// do some cheking
const service = await this.salonServicesQuery.getById(serviceId, salonId);// THIS one used to retrieve methods from the query class
updateService(serviceId, salonId, dto, service)
}
async updateService(serviceId: number, salonId: number, dto: UpdateServiceDto, service: ???) {
let category: any;
if (dto.categoryId) {
category = await this.categoryRepository.findOne({
where: { id: dto.categoryId, salon: { id: salonId } },
});
if (!category) {
throw new NotFoundException(
`Category with ID '${dto.categoryId}' not found in salon '${salonId}'`
);
}
}
// continue doing logical things
}
但是,如果有一些必须保留的业务关键不变量,那么您可能希望以这样的方式安排代码,使不变量的维护更加明显,而不是使用看起来像外部参考数据的习惯用法。