第 7 节,共 17 节
领域和边界
目录
领域是一个带有显式入口的文件夹。在文件夹内部,适用第 6 节的类型规则。跨文件夹时,只适用一条规则:你可以导入另一个领域的 api 库,除此之外什么都不行。
7.1. API 库
fleet/api 决定 fleet 向公司其他部分提供什么。没有列出的一切都是 Workshop 团队私有的,可以随时修改,无需征求任何人的意见。
libs/fleet/api/src/index.ts
export type { VehicleSummary, VehicleId } from '@fleetline/fleet/model';
export { VehicleSummaryStore } from '@fleetline/fleet/data-access';
export { VehicleBadgeComponent } from '@fleetline/fleet/ui-vehicle-badge';
它导出的 store 是 NgRx Signal Store,而 maintenance 使用的是经典的 NgRx Store。maintenance 不需要知道这一点;它只看到 VehicleSummaryStore。
libs/fleet/data-access/src/lib/vehicle-summary.store.ts
import { inject } from '@angular/core';
import { patchState, signalStore, withMethods } from '@ngrx/signals';
import { upsertEntities, withEntities } from '@ngrx/signals/entities';
import { rxMethod } from '@ngrx/signals/rxjs-interop';
import { tapResponse } from '@ngrx/operators';
import { filter, map, mergeMap, pipe } from 'rxjs';
import type { VehicleSummary } from '@fleetline/fleet/model';
import { FleetApi } from './fleet.api';
export const VehicleSummaryStore = signalStore(
{ providedIn: 'root' },
withEntities<VehicleSummary>(),
withMethods((store, api = inject(FleetApi)) => ({
ensureLoaded: rxMethod<readonly string[]>(
pipe(
map((ids) => [...new Set(ids)].filter((id) => !store.entityMap()[id])),
filter((ids) => ids.length > 0),
mergeMap((ids) =>
api.summaries(ids).pipe(
tapResponse({
next: (vehicles) => patchState(store, upsertEntities(vehicles)),
error: (error: unknown) => console.error('fleet summaries', error),
}),
),
),
),
),
})),
);
7.2. shared 也是一个领域
shared 带有 domain:shared 标签,并且只能导入 domain:shared。它不知道任何业务术语。评审时的经验法则:如果 shared 中的某个文件包含某个领域的词汇(工单、发票、车辆),就把它移到那个领域中。
7.3. 当两个领域需要同一样东西时
| 情况 | 答案 |
|---|---|
| billing 要显示车辆的车牌 | billing 导入 fleet/api。 |
| maintenance 和 inventory 都需要车场列表 | 车场是一个独立的概念:建一个小的 depots 领域,或者由 fleet 在它的 API 中导出。不是 shared。 |
| booking 在预约后需要创建工单 | booking 调用后端;由后端创建工单。前端领域之间不编排彼此的写操作。 |
| 两个领域需要同一个日期选择器 | 它是技术性的,而不是业务性的:shared/ui-design-system。 |
| 两个 API 库想要互相导入 | 领域切分错了。把它们合并,或者把共享的概念移到第三个领域中。 |