atelier-spec-architect
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseArchitect Skill
Architect Skill
Domain-Driven Design and hexagonal architecture with functional core pattern for feature design.
基于功能核心模式的领域驱动设计(DDD)与六边形架构,用于功能设计。
Architecture Model
架构模型
Unified view of functional core and effectful edge:
Effectful Edge (IO) Functional Core (Pure)
┌─────────────────────────────────┐ ┌──────────────────────────┐
│ Router → request parsing │ │ Service → orchestration│
│ Consumer → event handling │───▶│ Entity → domain rules │
│ Client → external APIs │ │ → validation │
│ Producer → event publishing │◀───│ → transforms │
│ Repository→ data persistence │ │ │
└─────────────────────────────────┘ └──────────────────────────┘Key Principle: Business logic lives in the functional core (Service + Entity). IO operations live in the effectful edge. Core defines interfaces; edge implements them (dependency inversion).
功能核心层与有副作用边缘层的统一视图:
Effectful Edge (IO) Functional Core (Pure)
┌─────────────────────────────────┐ ┌──────────────────────────┐
│ Router → request parsing │ │ Service → orchestration│
│ Consumer → event handling │───▶│ Entity → domain rules │
│ Client → external APIs │ │ → validation │
│ Producer → event publishing │◀───│ → transforms │
│ Repository→ data persistence │ │ │
└─────────────────────────────────┘ └──────────────────────────┘核心原则: 业务逻辑位于功能核心层(Service + Entity)。IO操作位于有副作用的边缘层。核心层定义接口,边缘层实现接口(依赖倒置)。
Functional Core
功能核心层
Pure, deterministic components containing all business logic.
包含所有业务逻辑的纯函数、确定性组件。
Service Layer
服务层
Responsibility: Orchestrate business operations, coordinate between entities and repositories.
Characteristics:
- Pure functions that take data and return results
- No IO operations (database, HTTP, file system)
- Calls repositories through interfaces (dependency injection)
- Composes entity operations into workflows
- Returns success/error results
Example:
typescript
class OrderService {
async createOrder(request: CreateOrderRequest): Promise<Result<Order>> {
// Validate with entity
const order = Order.fromRequest(request);
const validation = order.validate();
if (!validation.ok) return validation;
// Check business rules
const inventory = await this.inventoryRepo.checkAvailability(order.items);
if (!inventory.available) return Err('Items not available');
// Coordinate persistence
await this.inventoryRepo.reserve(order.items);
const saved = await this.orderRepo.save(order.toRecord());
return Ok(Order.fromRecord(saved));
}
}职责: 编排业务操作,协调实体与仓库之间的交互。
特性:
- 接收数据并返回结果的纯函数
- 无IO操作(数据库、HTTP、文件系统)
- 通过接口调用仓库(依赖注入)
- 将实体操作组合为工作流
- 返回成功/错误结果
示例:
typescript
class OrderService {
async createOrder(request: CreateOrderRequest): Promise<Result<Order>> {
// Validate with entity
const order = Order.fromRequest(request);
const validation = order.validate();
if (!validation.ok) return validation;
// Check business rules
const inventory = await this.inventoryRepo.checkAvailability(order.items);
if (!inventory.available) return Err('Items not available');
// Coordinate persistence
await this.inventoryRepo.reserve(order.items);
const saved = await this.orderRepo.save(order.toRecord());
return Ok(Order.fromRecord(saved));
}
}Entity Layer
实体层
Responsibility: Domain models, validation, business rules, data transformations.
Characteristics:
- Pure data structures with behavior
- All validation logic
- Data transformations (fromRequest, toRecord, toResponse)
- Business rules and invariants
- No IO, no framework dependencies
Example:
typescript
class Order {
constructor(
public readonly id: string,
public readonly customerId: string,
public readonly items: OrderItem[],
public readonly status: OrderStatus,
public readonly total: number
) {}
static fromRequest(req: CreateOrderRequest): Order {
return new Order(
generateId(),
req.customerId,
req.items.map(i => new OrderItem(i)),
'pending',
req.items.reduce((sum, i) => sum + i.price * i.quantity, 0)
);
}
toRecord(): OrderRecord {
return {
id: this.id,
customer_id: this.customerId,
items: JSON.stringify(this.items),
status: this.status,
total: this.total
};
}
validate(): Result<Order> {
if (this.items.length === 0) {
return Err('Order must have at least one item');
}
if (this.total < 0) {
return Err('Order total cannot be negative');
}
return Ok(this);
}
canCancel(): boolean {
return ['pending', 'confirmed'].includes(this.status);
}
}职责: 领域模型、验证、业务规则、数据转换。
特性:
- 带有行为的纯数据结构
- 包含所有验证逻辑
- 数据转换(fromRequest、toRecord、toResponse)
- 业务规则与不变量
- 无IO操作,无框架依赖
示例:
typescript
class Order {
constructor(
public readonly id: string,
public readonly customerId: string,
public readonly items: OrderItem[],
public readonly status: OrderStatus,
public readonly total: number
) {}
static fromRequest(req: CreateOrderRequest): Order {
return new Order(
generateId(),
req.customerId,
req.items.map(i => new OrderItem(i)),
'pending',
req.items.reduce((sum, i) => sum + i.price * i.quantity, 0)
);
}
toRecord(): OrderRecord {
return {
id: this.id,
customer_id: this.customerId,
items: JSON.stringify(this.items),
status: this.status,
total: this.total
};
}
validate(): Result<Order> {
if (this.items.length === 0) {
return Err('Order must have at least one item');
}
if (this.total < 0) {
return Err('Order total cannot be negative');
}
return Ok(this);
}
canCancel(): boolean {
return ['pending', 'confirmed'].includes(this.status);
}
}Effectful Edge
有副作用的边缘层
IO-performing components that interact with the outside world.
执行IO操作、与外部系统交互的组件。
Router
路由层
Responsibility: HTTP request handling, parsing, response formatting.
Characteristics:
- Parses HTTP requests into domain types
- Calls service layer with parsed data
- Formats service results into HTTP responses
- Handles HTTP-specific concerns (status codes, headers)
- No business logic
Example:
typescript
router.post('/orders', async (req, res) => {
const result = await orderService.createOrder(req.body);
if (result.ok) {
res.status(201).json(result.value.toResponse());
} else {
res.status(400).json({ error: result.error });
}
});职责: HTTP请求处理、解析、响应格式化。
特性:
- 将HTTP请求解析为领域类型
- 调用服务层处理解析后的数据
- 将服务层结果格式化为HTTP响应
- 处理HTTP相关事项(状态码、请求头)
- 无业务逻辑
示例:
typescript
router.post('/orders', async (req, res) => {
const result = await orderService.createOrder(req.body);
if (result.ok) {
res.status(201).json(result.value.toResponse());
} else {
res.status(400).json({ error: result.error });
}
});Repository
仓库层
Responsibility: Data persistence and retrieval.
Characteristics:
- Implements data access interface used by services
- Converts between domain entities and database records
- Handles database queries and transactions
- No business logic or validation
Example:
typescript
class OrderRepository {
async save(record: OrderRecord): Promise<OrderRecord> {
return await db.orders.create(record);
}
async findById(id: string): Promise<OrderRecord | null> {
return await db.orders.findOne({ id });
}
}职责: 数据持久化与检索。
特性:
- 实现服务层使用的数据访问接口
- 转换领域实体与数据库记录
- 处理数据库查询与事务
- 无业务逻辑或验证
示例:
typescript
class OrderRepository {
async save(record: OrderRecord): Promise<OrderRecord> {
return await db.orders.create(record);
}
async findById(id: string): Promise<OrderRecord | null> {
return await db.orders.findOne({ id });
}
}Component Matrix
组件矩阵
Quick reference for where things belong:
| Concern | Component | Layer | Testability |
|---|---|---|---|
| Domain model | Entity | Core | Unit test (pure) |
| Validation | Entity | Core | Unit test (pure) |
| Business rules | Entity | Core | Unit test (pure) |
| Orchestration | Service | Core | Unit test (stub repos) |
| Data transforms | Entity | Core | Unit test (pure) |
| HTTP parsing | Router | Edge | Integration test |
| Data access | Repository | Edge | Integration test |
| External APIs | Client | Edge | Integration test |
| Event handling | Consumer | Edge | Integration test |
| Event publishing | Producer | Edge | Integration test |
快速参考各内容所属位置:
| 关注点 | 组件 | 层级 | 可测试性 |
|---|---|---|---|
| 领域模型 | Entity | 核心层 | 单元测试(纯函数) |
| 验证 | Entity | 核心层 | 单元测试(纯函数) |
| 业务规则 | Entity | 核心层 | 单元测试(纯函数) |
| 编排 | Service | 核心层 | 单元测试(桩仓库) |
| 数据转换 | Entity | 核心层 | 单元测试(纯函数) |
| HTTP解析 | Router | 边缘层 | 集成测试 |
| 数据访问 | Repository | 边缘层 | 集成测试 |
| 外部API | Client | 边缘层 | 集成测试 |
| 事件处理 | Consumer | 边缘层 | 集成测试 |
| 事件发布 | Producer | 边缘层 | 集成测试 |
Task Breakdown
任务拆解
Bottom-Up Dependency Ordering
自底向上的依赖排序
Implementation order follows dependency chain:
1. Entity → Domain models, validation, transforms
2. Repository → Data access interfaces and implementations
3. Service → Business logic orchestration
4. Router → HTTP endpointsRationale: Each layer depends on layers below. Can't implement service without entity, can't implement router without service.
实现顺序遵循依赖链:
1. Entity → 领域模型、验证、转换
2. Repository → 数据访问接口与实现
3. Service → 业务逻辑编排
4. Router → HTTP端点原理: 每个层级依赖于下方的层级。没有实体层就无法实现服务层,没有服务层就无法实现路由层。
Task Granularity
任务粒度
One task per layer:
- Implement Order entity with validation
- Implement OrderRepository with data access
- Implement OrderService with business logic
- Implement order API endpoints
For complex features, break down further:
- Entity: Order, OrderItem, OrderStatus
- Repository: OrderRepository, InventoryRepository
- Service: OrderService, PaymentService
- Router: Order routes, Payment routes
每个层级对应一个任务:
- 实现带验证的Order实体
- 实现带数据访问的OrderRepository
- 实现带业务逻辑的OrderService
- 实现订单API端点
对于复杂功能,可进一步拆分:
- 实体层:Order、OrderItem、OrderStatus
- 仓库层:OrderRepository、InventoryRepository
- 服务层:OrderService、PaymentService
- 路由层:订单路由、支付路由
Architect → Testing Flow
架构→测试流程
Architectural decisions inform testing strategy:
Architect Outputs → Testing Inputs
────────────────────────────────────────────────
Component responsibilities → What to test
Layer boundaries → Where to test
Pure vs effectful → Unit vs integration
Entity transformations → Property-based tests
Service orchestration → Stub-driven testsThe testing skill uses architectural structure to determine:
- What gets unit tested (core) vs integration tested (edge)
- Where to place test boundaries
- What to stub and what to test for real
- What test cases validate business rules
架构决策指导测试策略:
架构输出 → 测试输入
────────────────────────────────────────────────
组件职责 → 测试内容
层级边界 → 测试位置
纯函数vs有副作用 → 单元测试vs集成测试
实体转换 → 属性化测试
服务编排 → 桩驱动测试测试技能利用架构结构确定:
- 哪些内容进行单元测试(核心层)vs 集成测试(边缘层)
- 测试边界的位置
- 哪些内容需要打桩,哪些需要真实测试
- 哪些测试用例用于验证业务规则
Reference Materials
参考资料
For detailed patterns and examples:
- See references/ddd-patterns.md - Aggregates, Value Objects, Domain Events, Bounded Contexts, composition patterns
- See references/data-modeling.md - Entity design principles, schema patterns, access pattern optimization, data transformation
- See references/api-design.md - REST conventions, request/response contracts, error handling, versioning patterns
如需详细的模式与示例:
- 参见 references/ddd-patterns.md - 聚合根、值对象、领域事件、限界上下文、组合模式
- 参见 references/data-modeling.md - 实体设计原则、模式、访问模式优化、数据转换
- 参见 references/api-design.md - REST规范、请求/响应契约、错误处理、版本控制模式