11 · 專案架構實戰
DDD 與整潔架構實戰
當核心商業規則的生命週期比眼下使用的 SQL 驅動套件、寄信廠商或 HTTP 框架還要長久時,採用 DDD / 整潔架構(六角形架構) 就能把外部底層細節擋在核心領域模型之外。在 dn-ioc 裡實作依賴反轉,完全不用寫抽象基礎類別或複雜的容器模組:最內層的 domain/ 宣告介面與 token() 連接埠(port),application/ 用 provide() 編排應用情境(use case),而最外層的 infra/ 將真實轉接器(adapter)打包成單一一個 bundleProviders() 匯出就大功告成。
1src/2├── domain/ # 不匯入專案內任何其他分層3│ ├── order.ts # Order 實體 + OrderRepository 連接埠介面與 token4│ └── ports.ts # Clock、Mailer 等橫切連接埠介面與 token5├── application/ # 僅匯入 domain/6│ ├── order-service.ts # OrderService 應用服務 Ref,注入 domain 層 token7│ └── order-service.test.ts # 純記憶體單元測試:綁定輕量測試替身8├── infra/ # 僅匯入 domain/9│ ├── sql-order-repository.ts # 內部私有 sqlTableRef + sqlOrderRepositoryProvider10│ ├── system-adapters.ts # systemClockProvider + smtpMailerProvider11│ └── providers.ts # infraProviders = bundleProviders(...)12└── main.ts # 組裝根(Composition Root):同時匯入 application/ 與 infra/
1. 純淨的領域實體與連接埠 Token(domain/)
domain/ 資料夾位於整張依賴圖的正中心,完全不匯入專案裡任何其他分層。除了像 Order 這樣的領域實體外,它也負責定義外部世界必須滿足的 Port(連接埠)——包含資料持久化儲存庫(OrderRepository),以及像系統時間(Clock)與寄信服務(Mailer)這類橫切關注點的副作用。
每個連接埠都是一組固定搭配:一個 TypeScript interface,加上一個直接以該介面命名的 token<T>('Name')。把讀取系統時間封裝在 clockToken 後面,商業邏輯裡就不會到處直接呼叫 new Date(),任何跟時間相關的狀態轉換在測試裡都能做到 100% 穩定可預測。
- domain/
1import { token } from 'dn-ioc'23export interface Order {4 id: string5 customerEmail: string6 status: 'draft' | 'submitted'7 submittedAt?: Date8}910export interface OrderRepository {11 find(id: string): Promise<Order | undefined>12 save(order: Order): Promise<void>13}1415export const orderRepositoryToken = token<OrderRepository>('OrderRepository')
1import { token } from 'dn-ioc'23export interface Clock {4 now(): Date5}67export interface Mailer {8 sendOrderConfirmation(email: string, orderId: string): Promise<void>9}1011export const clockToken = token<Clock>('Clock')12export const mailerToken = token<Mailer>('Mailer')
2. 應用層服務(application/)
application/ 層負責協調領域實體與各個連接埠,完成像 OrderService.submit(id) 這樣的應用情境。請特別留意這裡刻意採用的混合設計:
OrderService取得外部能力時,一律只透過領域層 Token(orderRepositoryToken、clockToken、mailerToken)注入——它完全不知道、也不在乎訂單實際上是存在 Postgres、SQLite 還是記憶體裡的Map。- 然而
orderServiceRef自己卻是透過provide(({ inject }) => { ... })匯出成一個Ref!為什麼?因為會呼叫application/的角色——像是 HTTP Controller、CLI 指令、佇列 Worker 與測試程式碼——全都位於更外層,本來就應該直接往內匯入應用層服務。既然模組匯入箭頭已經指向內側,就完全沒必要再多包一層多餘的 Token。
1import { provide } from 'dn-ioc'2import { type Order, orderRepositoryToken } from '../domain/order'3import { clockToken, mailerToken } from '../domain/ports'45export const orderServiceRef = provide(({ inject }) => {6 const orders = inject(orderRepositoryToken)7 const clock = inject(clockToken)8 const mailer = inject(mailerToken)910 return {11 async submit(id: string): Promise<Order> {12 const order = await orders.find(id)13 if (!order) {14 throw new Error(`Order ${id} not found`)15 }16 if (order.status === 'submitted') {17 throw new Error(`Order ${id} already submitted`)18 }1920 const submitted: Order = {21 ...order,22 status: 'submitted',23 submittedAt: clock.now(),24 }2526 await orders.save(submitted)27 await mailer.sendOrderConfirmation(submitted.customerEmail, submitted.id)28 return submitted29 },30 }31})
3. 基礎設施轉接器與整層打包(infra/)
infra/ 資料夾負責匯入 domain/ 的型別契約,並針對真實的資料庫驅動套件、第三方 SDK 與外部服務撰寫實作:
- 把底層連線控柄留在
infra/內部私有: 在sql-order-repository.ts裡,sqlTableRef是一個不對外匯出的內部Ref,負責管理底層資料表/連線池狀態並註冊onDispose清理掛鉤。sqlOrderRepositoryProvider在幕後注入sqlTableRef,而domain/與application/從頭到尾都不必知道sqlTableRef的存在。 - 將整層轉接器打包進
infraProviders:infra/providers.ts把sqlTableRef(確保根作用域裡所有轉接器共用同一個底層連線客戶端)連同每一個provideFor()綁定,整合成單一一個bundleProviders(...)控柄。 - 新增轉接器只需修改兩處: 日後新增任何基礎設施轉接器時,只需要在
infra/裡面做兩件事——寫好它的provideFor()綁定,並在infraProviders多加一行。外部所有的程式進入點完全不用改動。
- infra/
1import { provide, provideFor } from 'dn-ioc'2import { type Order, orderRepositoryToken } from '../domain/order'34// Private infrastructure client — never imported by domain or application5export const sqlTableRef = provide(({ onDispose }) => {6 const rows = new Map<string, Order>([['ord-1', { id: 'ord-1', customerEmail: 'ada@example.com', status: 'draft' }]])7 onDispose(() => {8 rows.clear()9 })10 return rows11})1213export const sqlOrderRepositoryProvider = provideFor(orderRepositoryToken, ({ inject }) => {14 const rows = inject(sqlTableRef)15 return {16 find: async id => rows.get(id),17 save: async order => {18 rows.set(order.id, order)19 },20 }21})
1import { provideFor } from 'dn-ioc'2import { clockToken, type Mailer, mailerToken } from '../domain/ports'34const smtpMailer: Mailer = {5 async sendOrderConfirmation(email, orderId) {6 // Stands in for an SMTP or transactional email HTTP client7 void email8 void orderId9 },10}1112export const systemClockProvider = provideFor(clockToken, () => ({ now: () => new Date() }))13export const smtpMailerProvider = provideFor(mailerToken, () => smtpMailer)
1import { bundleProviders } from 'dn-ioc'2import { sqlOrderRepositoryProvider, sqlTableRef } from './sql-order-repository'3import { smtpMailerProvider, systemClockProvider } from './system-adapters'45// One bundle collects every infrastructure adapter; entrypoints install it once6export const infraProviders = bundleProviders(7 sqlTableRef,8 sqlOrderRepositoryProvider,9 systemClockProvider,10 smtpMailerProvider,11)
4. 組裝根(Composition Root)與多進入點重用
main.ts 就是整個專案的 Composition Root(組裝根)——全專案唯一同時匯入 application/ 與 infra/,並透過 providers: [infraProviders] 把兩端扣合在一起的地方。
因為 infraProviders 是可直接重用的打包物件,而且 orderServiceRef 與傳輸協定完全解耦,要在同一個領域核心上開啟多個不同進入點,每個都只要寥寥幾行程式碼:
- HTTP API 伺服器(
main.ts): 掛載[infraProviders],並在bootstrapApp()裡當場呼叫inject(orderServiceRef)(萬一漏綁了任何一個 Token,await app.start()啟動時就會立刻報錯拒絕,不會等到線上客戶結帳到一半才出事),最後交給路由層處理請求。 - 佇列 Worker 或 CLI 批次工具(
worker.ts): 在各自的進入點呼叫bootstrapApp(..., { providers: [infraProviders] })並注入同一個orderServiceRef——若是執行資料回補腳本不想真的寄信給客戶,只要在infraProviders後面 補上一行provideFor(mailerToken, dryRunMailer)就能原地覆寫寄信服務。 - 純單元測試(
application/order-service.test.ts): 完全不載入infraProviders,只掛載輕量的記憶體provideFor()測試替身。只要漏綁任何一個連接埠,unitTestApp.start()就會立刻以No provider for token: Mailer快速失敗。
- application/
1import { bootstrapApp } from 'dn-ioc'2import { orderServiceRef } from './application/order-service'3import { infraProviders } from './infra/providers'45// Composition Root: the only module that imports both application and infra6export const app = bootstrapApp(7 async ({ inject }) => {8 const orders = inject(orderServiceRef)9 const submitted = await orders.submit('ord-1')10 console.log(submitted.status) // submitted11 },12 {13 providers: [infraProviders],14 },15)1617await app.start()18await app.stop()
1import { bootstrapApp, provideFor } from 'dn-ioc'2import { orderServiceRef } from './application/order-service'3import { type Order, type OrderRepository, orderRepositoryToken } from './domain/order'4import { clockToken, type Mailer, mailerToken } from './domain/ports'56const saved: Order[] = []7const sentEmails: string[] = []8const fixedNow = new Date('2026-11-18T12:00:00.000Z')910const fakeOrderRepository = (): OrderRepository => ({11 find: async id => ({ id, customerEmail: 'ada@example.com', status: 'draft' }),12 save: async order => {13 saved.push(order)14 },15})1617const fakeMailer = (): Mailer => ({18 sendOrderConfirmation: async (email, orderId) => {19 sentEmails.push(`${email}:${orderId}`)20 },21})2223export const unitTestApp = bootstrapApp(24 async ({ inject }) => {25 const result = await inject(orderServiceRef).submit('ord-42')26 console.log(result.status, saved.length, sentEmails) // submitted 1 [ 'ada@example.com:ord-42' ]27 },28 {29 // Pure fakes only — forgetting any token fails fast with "No provider for token: <Name>"30 providers: [31 provideFor(orderRepositoryToken, fakeOrderRepository),32 provideFor(clockToken, () => ({ now: () => fixedNow })),33 provideFor(mailerToken, fakeMailer),34 ],35 },36)3738await unitTestApp.start()39await unitTestApp.stop()
5. 分層匯入邊界速查
由於 dn-ioc 只在執行期處理控柄、不會介入靜態 import 檢查,平時協作請依下表守住各層目錄的匯入方向:
| 分層目錄 | 允許匯入的專案路徑 | 禁止匯入的專案路徑 |
|---|---|---|
domain/ | 無(僅可匯入 'dn-ioc' 的 token) | application/、infra/、main.ts |
application/ | domain/ | infra/、main.ts |
infra/ | domain/ | application/、main.ts |
main.ts(各進入點) | application/、infra/、domain/ | — |
看完這兩種專案架構後,下一章我們把單元測試與整合測試放在一起對照——請翻到測試與模擬替身。