0Pricing
TypeScript Academy · 课时

领域建模——聚合、不变量与服务

使用带品牌的 ID 建模 Cart 等聚合,并通过工厂和服务强制执行不变量。

领域建模——聚合、不变量与服务 是 CoddyKit 上的免费 TypeScript Academy 课时。 这是第 3 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 TypeScript Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 TypeScript Academy 课程共包含 3 节课。

简介

目标:使用带品牌的 ID表示 Cart 聚合,并确保数量大于 0 等规则在工厂和服务中得到强制执行。

  • 带品牌的 ID 可以区分实体边界
  • 工厂返回结果联合类型
  • 服务函数避免无效状态转换

实体与品牌

即使 CartId 和 ProductId 都是字符串,带品牌的 ID 也会使它们互不兼容。这可以防止混用。

type Brand<Tag extends string, T> = T & { readonly __brand: Tag }

type CartId = Brand<"CartId", string>
type ProductId = Brand<"ProductId", string>

type Result<T> = { ok: true; value: T } | { ok: false; error: string }

const cartId = (s: string): CartId => s as CartId
const productId = (s: string): ProductId => s as ProductId

聚合与不变量

工厂会验证规则:数量必须大于 0。只有有效的 Line 对象才能被创建。

type Money = number & { readonly __brand: "Money" }
const money = (n: number): Money => n as Money

interface Line { productId: ProductId; qty: number; price: Money }
interface Cart { id: CartId; lines: Line[]; total: Money }

function makeLine(productId: ProductId, qty: number, price: Money): Result<Line> {
  if (!Number.isInteger(qty) || qty <= 0) return { ok: false, error: "qty must be > 0" }
  return { ok: true, value: { productId, qty, price } }
}

function makeCart(id: CartId): Cart { return { id, lines: [], total: money(0) } }

服务:添加项目

服务函数执行安全的状态转换并重新计算总数。如果总数无效,函数会返回错误,而不是破坏状态。

function addItem(cart: Cart, line: Line): Result<Cart> {
  const lines = [...cart.lines, line]
  const totalNum = lines.reduce((s, x) => s + (x.qty * (x.price as number)), 0)
  if (!Number.isFinite(totalNum) || totalNum < 0) return { ok: false, error: "invalid total" }
  return { ok: true, value: { ...cart, lines, total: (totalNum as unknown) as Money } }
}

// Usage
const c0 = makeCart(cartId("c1"))
const l = makeLine(productId("p1"), 2, money(10))
const c1 = l.ok ? addItem(c0, l.value) : { ok: false, error: "bad line" }

边界映射

在边界处(例如 APIs),将数据转换为数据传输对象,并在解析回来时进行验证。工厂可以确保数据正确。

type CartDTO = { id: string; lines: { productId: string; qty: number; price: number }[]; total: number }

function serialize(c: Cart): CartDTO {
  return {
    id: c.id as unknown as string,
    lines: c.lines.map(x => ({ productId: x.productId as unknown as string, qty: x.qty, price: x.price as unknown as number })),
    total: c.total as unknown as number
  }
}

function parse(dto: CartDTO): Result<Cart> {
  const id = cartId(dto.id)
  const lines: Line[] = []
  for (const raw of dto.lines) {
    const l = makeLine(productId(raw.productId), raw.qty, money(raw.price))
    if (!l.ok) return { ok: false, error: l.error }
    lines.push(l.value)
  }
  const totalNum = lines.reduce((s, x) => s + (x.qty * (x.price as number)), 0)
  return { ok: true, value: { id, lines, total: money(totalNum) } }
}

提示

最佳实践:

  • 将验证集中在工厂中。
  • 保持服务函数纯粹且具有确定性。
  • 仅在系统边界处进行品牌转换。

不变量检查

快速检查:应如何强制执行数量大于 0 这样的不变量?

回顾

回顾:带品牌的 ID 与工厂和服务结合,可以强制执行不变量。由于所有入口都会验证输入,因此无法创建无效状态。

常见问题解答

「领域建模——聚合、不变量与服务」课时是免费的吗?

是的 — 「领域建模——聚合、不变量与服务」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 TypeScript Academy 课程的其余内容,请升级到 CoddyKit PRO。 TypeScript Academy 课程共包含 3 节课。

「领域建模——聚合、不变量与服务」这节课中我会学到什么?

使用带品牌的 ID 建模 Cart 等聚合,并通过工厂和服务强制执行不变量。 你通过在浏览器中直接运行的动手代码来练习 TypeScript Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 TypeScript Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 TypeScript Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 3 节。

「领域建模——聚合、不变量与服务」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 TypeScript Academy 课中编写并运行代码吗?

能。每节 TypeScript Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 品牌类型/不透明类型,防止单位混用
  2. 带标签的 ID 与领域建模模式
  3. 领域建模——聚合、不变量与服务
← 返回 TypeScript Academy