@martinffx/atelier 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +22 -24
  3. package/agents/architect.md +1 -1
  4. package/agents/oracle.md +1 -1
  5. package/dist/atelier.js +12 -14
  6. package/package.json +1 -1
  7. package/skills/code-commit/SKILL.md +5 -13
  8. package/skills/code-pull-request/SKILL.md +36 -0
  9. package/skills/code-pull-request/references/common.md +76 -0
  10. package/skills/code-pull-request/references/create-pr.md +122 -0
  11. package/skills/code-pull-request/references/default-template.md +25 -0
  12. package/skills/code-pull-request/references/leave-comment.md +53 -0
  13. package/skills/code-pull-request/references/merge-pr.md +94 -0
  14. package/skills/code-pull-request/references/read-comments.md +61 -0
  15. package/skills/code-pull-request/references/respond-to-comment.md +66 -0
  16. package/skills/code-review/SKILL.md +21 -12
  17. package/skills/code-review/references/reviewers.md +142 -41
  18. package/skills/code-review/references/rq.md +48 -32
  19. package/skills/oracle-debug/SKILL.md +218 -0
  20. package/skills/{code-debug → oracle-debug}/references/bug-patterns.md +3 -3
  21. package/skills/oracle-domain-modelling/SKILL.md +84 -0
  22. package/skills/oracle-grill-me/SKILL.md +20 -0
  23. package/skills/spec-brainstorm/SKILL.md +91 -71
  24. package/skills/spec-finish/SKILL.md +20 -14
  25. package/skills/spec-implement/SKILL.md +3 -2
  26. package/skills/spec-orchestrator/SKILL.md +4 -15
  27. package/skills/spec-plan/SKILL.md +1 -1
  28. package/agents/scout.md +0 -40
  29. package/skills/code-commit/references/pr-workflow.md +0 -145
  30. package/skills/code-debug/SKILL.md +0 -199
  31. package/skills/code-docs/SKILL.md +0 -171
  32. package/skills/code-docs/references/api-docs.md +0 -116
  33. package/skills/code-docs/references/changelog.md +0 -64
  34. package/skills/code-docs/references/readme-structure.md +0 -94
  35. package/skills/oracle-architect/SKILL.md +0 -327
  36. package/skills/oracle-architect/references/api-design.md +0 -345
  37. package/skills/oracle-architect/references/data-modeling.md +0 -318
  38. package/skills/oracle-architect/references/ddd-patterns.md +0 -348
  39. package/skills/oracle-architect/references/interface-design.md +0 -203
  40. package/skills/oracle-challenge/SKILL.md +0 -126
  41. package/skills/oracle-doubt/SKILL.md +0 -252
  42. package/skills/oracle-doubt/references/adversarial-prompt.md +0 -47
  43. package/skills/oracle-grillme/SKILL.md +0 -160
  44. package/skills/oracle-security/SKILL.md +0 -225
  45. package/skills/oracle-security/references/security-patterns.md +0 -236
  46. package/skills/oracle-security/references/threat-modeling-guide.md +0 -137
  47. package/skills/oracle-testing/SKILL.md +0 -237
  48. package/skills/oracle-testing/references/anti-patterns.md +0 -618
  49. package/skills/oracle-testing/references/boundaries.md +0 -579
  50. package/skills/oracle-testing/references/core-testing.md +0 -691
  51. package/skills/oracle-testing/references/edge-testing.md +0 -794
  52. package/skills/oracle-testing/references/stub-driven-tdd.md +0 -322
  53. package/skills/oracle-thinkdeep/SKILL.md +0 -164
  54. /package/skills/{code-debug → oracle-debug}/references/language-tools.md +0 -0
  55. /package/skills/{code-debug → oracle-debug}/references/techniques.md +0 -0
  56. /package/skills/{oracle-grillme → oracle-domain-modelling}/references/ADR-FORMAT.md +0 -0
  57. /package/skills/{oracle-grillme → oracle-domain-modelling}/references/CONTEXT-FORMAT.md +0 -0
@@ -1,327 +0,0 @@
1
- ---
2
- name: oracle-architect
3
- description: DDD and hexagonal architecture with functional core pattern. Use when designing features, modeling domains, breaking down tasks, or understanding component responsibilities.
4
- user-invocable: false
5
- ---
6
-
7
- # Architect Skill
8
-
9
- ## Glossary
10
-
11
- Precise vocabulary for every architectural decision. Use these terms exactly — consistency is the point.
12
-
13
- - **Module** — anything with an interface and an implementation (function, class, package, layer). Router, Service, Entity, and Repository are all modules.
14
- - **Interface** — everything a caller must know to use the module: types, invariants, error modes, ordering, config. Not just the type signature.
15
- - **Seam** — where a module's interface lives; a place behaviour can be altered without editing in place. The functional core / effectful edge boundary is the primary seam.
16
- - **Depth** — leverage at the interface. A module is **deep** when a lot of behaviour sits behind a small interface. A module is **shallow** when the interface is nearly as complex as the implementation.
17
- - **Adapter** — a concrete thing satisfying an interface at a seam. A Postgres repository is an adapter; an in-memory fake for testing is another adapter at the same seam.
18
- - **Leverage** — what callers get from depth: more capability per unit of interface they learn.
19
- - **Locality** — what maintainers get from depth: change, bugs, and knowledge concentrate in one place.
20
-
21
- Key principles (apply to every decision):
22
-
23
- - **The deletion test.** Imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep.
24
- - **The interface is the test surface.** Callers and tests cross the same seam. If you want to test past the interface, the module is probably the wrong shape.
25
- - **One adapter = hypothetical seam. Two adapters = real seam.** Don't introduce a seam unless something actually varies across it.
26
-
27
- Domain-Driven Design and hexagonal architecture with functional core pattern for feature design.
28
-
29
- ## Architecture Model
30
-
31
- Unified view of functional core and effectful edge:
32
-
33
- ```
34
- Effectful Edge (IO) Functional Core (Pure)
35
- ┌─────────────────────────────────┐ ┌──────────────────────────┐
36
- │ Router → request parsing │ │ Service → orchestration│
37
- │ Consumer → event handling │───▶│ Entity → domain rules │
38
- │ Client → external APIs │ │ → validation │
39
- │ Producer → event publishing │◀───│ → transforms │
40
- │ Repository→ data persistence │ │ │
41
- └─────────────────────────────────┘ └──────────────────────────┘
42
- ```
43
-
44
- **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).
45
-
46
- ## Evaluating Architecture Decisions
47
-
48
- Before creating a new module, run these checks:
49
-
50
- ### Deletion Test
51
-
52
- > *Imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep.*
53
-
54
- **When to apply:** Before extracting a new Service, Repository, or utility class.
55
-
56
- **Example:**
57
- ```
58
- ❌ Shallow: OrderFormatterService with 1 method per field
59
- → Deleting it just moves 6 lines into the Router
60
- → Interface is as complex as implementation
61
-
62
- ✅ Deep: OrderService with validate → reserve → save → publish
63
- → Deleting it replicates orchestration across N handlers
64
- → Small interface (createOrder), large implementation
65
- ```
66
-
67
- ### Interface as Test Surface
68
-
69
- > *Callers and tests cross the same seam. If you want to test past the interface, the module is probably the wrong shape.*
70
-
71
- **Implication:**
72
- - Unit tests for Entities test the public interface (validate, transform)
73
- - Unit tests for Services test through the seam with stub repositories
74
- - Integration tests for Repositories test the actual adapter
75
- - If you find yourself testing "internal" methods, the module needs redrawing
76
-
77
- ### Adapter Rule
78
-
79
- > *One adapter = hypothetical seam. Two adapters = real seam.*
80
-
81
- **When to apply:** Deciding whether to extract an interface.
82
-
83
- **Examples:**
84
- ```typescript
85
- // ❌ Hypothetical seam — only one adapter exists
86
- interface IEmailClient { send(email: Email): Promise<void>; }
87
- class SendgridClient implements IEmailClient { ... }
88
- // No second adapter. The interface adds indirection without value.
89
-
90
- // ✅ Real seam — two adapters exist
91
- interface IOrderRepository { save(order: Order): Promise<Order>; }
92
- class PostgresOrderRepository implements IOrderRepository { ... }
93
- class InMemoryOrderRepository implements IOrderRepository { ... } // for tests
94
- // The seam earns its keep because callers vary (production vs test).
95
- ```
96
-
97
- ### Depth Check
98
-
99
- Prefer deep modules over shallow ones:
100
-
101
- | Module | Interface Size | Implementation | Depth |
102
- |--------|--------------|----------------|-------|
103
- | `OrderValidator` | 3 methods (validate, validateItems, validateAddress) | 30 lines each | Shallow |
104
- | `Order` (entity) | 4 methods (fromRequest, toRecord, toResponse, validate) | 200 lines of rules, transforms, invariants | **Deep** |
105
-
106
- **Rule of thumb:** A module's interface should hide at least 3x the complexity it exposes.
107
-
108
- ## Functional Core
109
-
110
- Pure, deterministic components containing all business logic.
111
-
112
- ### Service Layer
113
-
114
- **Responsibility:** Orchestrate business operations, coordinate between entities and repositories.
115
-
116
- **Characteristics:**
117
- - Pure functions that take data and return results
118
- - No IO operations (database, HTTP, file system)
119
- - Calls repositories through interfaces (dependency injection)
120
- - Composes entity operations into workflows
121
- - Returns success/error results
122
-
123
- **Example:**
124
- ```typescript
125
- class OrderService {
126
- async createOrder(request: CreateOrderRequest): Promise<Result<Order>> {
127
- // Validate with entity
128
- const order = Order.fromRequest(request);
129
- const validation = order.validate();
130
- if (!validation.ok) return validation;
131
-
132
- // Check business rules
133
- const inventory = await this.inventoryRepo.checkAvailability(order.items);
134
- if (!inventory.available) return Err('Items not available');
135
-
136
- // Coordinate persistence
137
- await this.inventoryRepo.reserve(order.items);
138
- const saved = await this.orderRepo.save(order.toRecord());
139
-
140
- return Ok(Order.fromRecord(saved));
141
- }
142
- }
143
- ```
144
-
145
- ### Entity Layer
146
-
147
- **Responsibility:** Domain models, validation, business rules, data transformations.
148
-
149
- **Characteristics:**
150
- - Pure data structures with behavior
151
- - All validation logic
152
- - Data transformations (fromRequest, toRecord, toResponse)
153
- - Business rules and invariants
154
- - No IO, no framework dependencies
155
-
156
- **Example:**
157
- ```typescript
158
- class Order {
159
- constructor(
160
- public readonly id: string,
161
- public readonly customerId: string,
162
- public readonly items: OrderItem[],
163
- public readonly status: OrderStatus,
164
- public readonly total: number
165
- ) {}
166
-
167
- static fromRequest(req: CreateOrderRequest): Order {
168
- return new Order(
169
- generateId(),
170
- req.customerId,
171
- req.items.map(i => new OrderItem(i)),
172
- 'pending',
173
- req.items.reduce((sum, i) => sum + i.price * i.quantity, 0)
174
- );
175
- }
176
-
177
- toRecord(): OrderRecord {
178
- return {
179
- id: this.id,
180
- customer_id: this.customerId,
181
- items: JSON.stringify(this.items),
182
- status: this.status,
183
- total: this.total
184
- };
185
- }
186
-
187
- validate(): Result<Order> {
188
- if (this.items.length === 0) {
189
- return Err('Order must have at least one item');
190
- }
191
- if (this.total < 0) {
192
- return Err('Order total cannot be negative');
193
- }
194
- return Ok(this);
195
- }
196
-
197
- canCancel(): boolean {
198
- return ['pending', 'confirmed'].includes(this.status);
199
- }
200
- }
201
- ```
202
-
203
- ## Effectful Edge
204
-
205
- IO-performing components that interact with the outside world.
206
-
207
- ### Router
208
-
209
- **Responsibility:** HTTP request handling, parsing, response formatting.
210
-
211
- **Characteristics:**
212
- - Parses HTTP requests into domain types
213
- - Calls service layer with parsed data
214
- - Formats service results into HTTP responses
215
- - Handles HTTP-specific concerns (status codes, headers)
216
- - No business logic
217
-
218
- **Example:**
219
- ```typescript
220
- router.post('/orders', async (req, res) => {
221
- const result = await orderService.createOrder(req.body);
222
-
223
- if (result.ok) {
224
- res.status(201).json(result.value.toResponse());
225
- } else {
226
- res.status(400).json({ error: result.error });
227
- }
228
- });
229
- ```
230
-
231
- ### Repository
232
-
233
- **Responsibility:** Data persistence and retrieval.
234
-
235
- **Characteristics:**
236
- - Implements data access interface used by services
237
- - Converts between domain entities and database records
238
- - Handles database queries and transactions
239
- - No business logic or validation
240
-
241
- **Example:**
242
- ```typescript
243
- class OrderRepository {
244
- async save(record: OrderRecord): Promise<OrderRecord> {
245
- return await db.orders.create(record);
246
- }
247
-
248
- async findById(id: string): Promise<OrderRecord | null> {
249
- return await db.orders.findOne({ id });
250
- }
251
- }
252
- ```
253
-
254
- ## Component Matrix
255
-
256
- Quick reference for where things belong:
257
-
258
- | Concern | Component | Layer | Testability |
259
- |---------|-----------|-------|-------------|
260
- | Domain model | Entity | Core | Unit test (pure) |
261
- | Validation | Entity | Core | Unit test (pure) |
262
- | Business rules | Entity | Core | Unit test (pure) |
263
- | Orchestration | Service | Core | Unit test (stub repos) |
264
- | Data transforms | Entity | Core | Unit test (pure) |
265
- | HTTP parsing | Router | Edge | Integration test |
266
- | Data access | Repository | Edge | Integration test |
267
- | External APIs | Client | Edge | Integration test |
268
- | Event handling | Consumer | Edge | Integration test |
269
- | Event publishing | Producer | Edge | Integration test |
270
-
271
- ## Task Breakdown
272
-
273
- ### Bottom-Up Dependency Ordering
274
-
275
- Implementation order follows dependency chain:
276
-
277
- ```
278
- 1. Entity → Domain models, validation, transforms
279
- 2. Repository → Data access interfaces and implementations
280
- 3. Service → Business logic orchestration
281
- 4. Router → HTTP endpoints
282
- ```
283
-
284
- **Rationale:** Each layer depends on layers below. Can't implement service without entity, can't implement router without service.
285
-
286
- ### Task Granularity
287
-
288
- **One task per layer:**
289
- - Implement Order entity with validation
290
- - Implement OrderRepository with data access
291
- - Implement OrderService with business logic
292
- - Implement order API endpoints
293
-
294
- **For complex features, break down further:**
295
- - Entity: Order, OrderItem, OrderStatus
296
- - Repository: OrderRepository, InventoryRepository
297
- - Service: OrderService, PaymentService
298
- - Router: Order routes, Payment routes
299
-
300
- ## Architect → Testing Flow
301
-
302
- Architectural decisions inform testing strategy:
303
-
304
- ```
305
- Architect Outputs → Testing Inputs
306
- ────────────────────────────────────────────────
307
- Component responsibilities → What to test
308
- Layer boundaries → Where to test
309
- Pure vs effectful → Unit vs integration
310
- Entity transformations → Property-based tests
311
- Service orchestration → Stub-driven tests
312
- ```
313
-
314
- The testing skill uses architectural structure to determine:
315
- - What gets unit tested (core) vs integration tested (edge)
316
- - Where to place test boundaries
317
- - What to stub and what to test for real
318
- - What test cases validate business rules
319
-
320
- ## Reference Materials
321
-
322
- For detailed patterns and examples:
323
-
324
- - **See [references/ddd-patterns.md](references/ddd-patterns.md)** - Aggregates, Value Objects, Domain Events, Bounded Contexts, composition patterns, seam placement
325
- - **See [references/data-modeling.md](references/data-modeling.md)** - Entity design principles, schema patterns, access pattern optimization, data transformation
326
- - **See [references/api-design.md](references/api-design.md)** - REST conventions, request/response contracts, error handling, versioning patterns
327
- - **See [references/interface-design.md](references/interface-design.md)** - Designing module interfaces, "Design It Twice" pattern, depth heuristics, dependency categories, anti-patterns
@@ -1,345 +0,0 @@
1
- # API Design Reference
2
-
3
- REST conventions, request/response contracts, and error handling patterns.
4
-
5
- ## REST Conventions
6
-
7
- ### Resource-Oriented Endpoints
8
-
9
- **Standard CRUD operations:**
10
- ```
11
- GET /orders # List orders
12
- POST /orders # Create order
13
- GET /orders/:id # Get single order
14
- PATCH /orders/:id # Update order
15
- DELETE /orders/:id # Delete order
16
- ```
17
-
18
- **Nested resources:**
19
- ```
20
- GET /orders/:orderId/items # List order items
21
- POST /orders/:orderId/items # Add item to order
22
- GET /orders/:orderId/items/:itemId # Get order item
23
- PATCH /orders/:orderId/items/:itemId # Update order item
24
- DELETE /orders/:orderId/items/:itemId # Delete order item
25
- ```
26
-
27
- ### Actions (Non-CRUD Operations)
28
-
29
- **Use POST for state transitions:**
30
- ```
31
- POST /orders/:id/cancel # Cancel order
32
- POST /orders/:id/ship # Ship order
33
- POST /orders/:id/confirm # Confirm order
34
- ```
35
-
36
- **Reasoning:** These modify state but aren't CRUD operations. They represent domain actions.
37
-
38
- **Avoid:**
39
- ```
40
- PATCH /orders/:id { "action": "cancel" } # Unclear what changed
41
- GET /orders/:id/cancel # GET shouldn't have side effects
42
- ```
43
-
44
- ## Request/Response Contracts
45
-
46
- ### Request Types
47
-
48
- **Create request (POST /resource):**
49
- ```typescript
50
- interface CreateOrderRequest {
51
- customerId: string;
52
- items: Array<{
53
- productId: string;
54
- quantity: number;
55
- }>;
56
- shippingAddress?: {
57
- street: string;
58
- city: string;
59
- zipCode: string;
60
- };
61
- }
62
- ```
63
-
64
- **Update request (PATCH /resource/:id):**
65
- ```typescript
66
- interface UpdateOrderRequest {
67
- status?: 'pending' | 'confirmed' | 'shipped';
68
- shippingAddress?: Address;
69
- // Only fields that can be updated
70
- }
71
- ```
72
-
73
- **Query parameters:**
74
- ```
75
- GET /orders?customerId=cust-123&status=pending&limit=20&offset=0
76
-
77
- interface ListOrdersQuery {
78
- customerId?: string;
79
- status?: OrderStatus;
80
- limit?: number; // Default 20, max 100
81
- offset?: number; // Pagination offset
82
- }
83
- ```
84
-
85
- ### Response Types
86
-
87
- **Single resource (GET /resource/:id):**
88
- ```typescript
89
- interface OrderResponse {
90
- id: string;
91
- customerId: string;
92
- items: OrderItem[];
93
- status: 'pending' | 'confirmed' | 'shipped' | 'delivered';
94
- total: number;
95
- createdAt: string; // ISO 8601
96
- updatedAt: string;
97
- }
98
- ```
99
-
100
- **List response (GET /resource):**
101
- ```typescript
102
- interface ListOrdersResponse {
103
- data: OrderResponse[];
104
- pagination: {
105
- total: number;
106
- limit: number;
107
- offset: number;
108
- hasMore: boolean;
109
- };
110
- }
111
- ```
112
-
113
- **Create response (POST /resource):**
114
- ```typescript
115
- // Return created resource with 201 status
116
- interface CreateOrderResponse extends OrderResponse {
117
- id: string; // Generated by server
118
- }
119
- ```
120
-
121
- ### Timestamp Conventions
122
-
123
- **Use ISO 8601 for all timestamps:**
124
- ```json
125
- {
126
- "createdAt": "2024-01-21T10:30:45Z",
127
- "updatedAt": "2024-01-21T10:30:45Z",
128
- "deletedAt": null
129
- }
130
- ```
131
-
132
- **Never:** Unix timestamps, custom formats, or timezone abbreviations
133
-
134
- ## Error Handling
135
-
136
- ### HTTP Status Codes
137
-
138
- **Success:**
139
- - `200 OK` - GET, PATCH succeeded
140
- - `201 Created` - POST created resource
141
- - `204 No Content` - DELETE or update with no response body
142
-
143
- **Client Errors:**
144
- - `400 Bad Request` - Invalid input validation
145
- - `401 Unauthorized` - Missing authentication
146
- - `403 Forbidden` - Authenticated but insufficient permissions
147
- - `404 Not Found` - Resource not found
148
- - `409 Conflict` - State violation (can't transition state)
149
- - `422 Unprocessable Entity` - Validation failed
150
-
151
- **Server Errors:**
152
- - `500 Internal Server Error` - Unhandled exception
153
- - `503 Service Unavailable` - Temporary outage
154
-
155
- ### Error Response Format
156
-
157
- **Validation error (400):**
158
- ```typescript
159
- interface ValidationErrorResponse {
160
- error: 'Validation failed';
161
- code: 'VALIDATION_ERROR';
162
- details: {
163
- field: string;
164
- message: string;
165
- }[];
166
- }
167
-
168
- // Example
169
- {
170
- "error": "Validation failed",
171
- "code": "VALIDATION_ERROR",
172
- "details": [
173
- { "field": "items", "message": "Must have at least one item" },
174
- { "field": "customerId", "message": "Invalid customer ID format" }
175
- ]
176
- }
177
- ```
178
-
179
- **Business rule violation (409):**
180
- ```typescript
181
- interface ConflictErrorResponse {
182
- error: string;
183
- code: string;
184
- details?: Record<string, unknown>;
185
- }
186
-
187
- // Example
188
- {
189
- "error": "Cannot cancel shipped order",
190
- "code": "ORDER_ALREADY_SHIPPED",
191
- "details": {
192
- "status": "shipped",
193
- "orderId": "order-123"
194
- }
195
- }
196
- ```
197
-
198
- **Not found (404):**
199
- ```json
200
- {
201
- "error": "Order not found",
202
- "code": "ORDER_NOT_FOUND",
203
- "details": { "id": "order-123" }
204
- }
205
- ```
206
-
207
- **Generic error (500):**
208
- ```json
209
- {
210
- "error": "Internal server error",
211
- "code": "INTERNAL_ERROR"
212
- }
213
- ```
214
-
215
- ### Error Code Convention
216
-
217
- Use SCREAMING_SNAKE_CASE for error codes:
218
- - `VALIDATION_ERROR` - Input validation failed
219
- - `ORDER_NOT_FOUND` - Resource not found
220
- - `ORDER_ALREADY_SHIPPED` - State violation
221
- - `INSUFFICIENT_INVENTORY` - Business rule violation
222
- - `AUTHENTICATION_REQUIRED` - Auth failed
223
- - `PERMISSION_DENIED` - Authz failed
224
-
225
- ## Versioning Patterns
226
-
227
- ### URL Versioning
228
-
229
- **Include version in path:**
230
- ```
231
- GET /v1/orders
232
- GET /v2/orders
233
- ```
234
-
235
- **Pros:** Explicit, clear to consumers
236
- **Cons:** Requires multiple code paths
237
-
238
- ### Accept Header Versioning
239
-
240
- **Use media type version:**
241
- ```
242
- GET /orders
243
- Accept: application/vnd.myapi.v2+json
244
- ```
245
-
246
- **Pros:** Cleaner URLs, single endpoint
247
- **Cons:** Less discoverable
248
-
249
- ### Pragmatic Approach
250
-
251
- 1. Start without versioning (all responses same format)
252
- 2. Add versioning when you need breaking changes
253
- 3. Support at least 2 versions during transition
254
- 4. Provide clear deprecation timeline
255
-
256
- ### Backwards Compatibility
257
-
258
- **Adding fields (safe):**
259
- ```typescript
260
- // v1
261
- interface OrderResponse {
262
- id: string;
263
- total: number;
264
- }
265
-
266
- // v2 (backwards compatible)
267
- interface OrderResponse {
268
- id: string;
269
- total: number;
270
- tax?: number; // New optional field
271
- }
272
- ```
273
-
274
- **Removing fields (breaking change):**
275
- ```typescript
276
- // Requires new API version
277
- // v1 has 'total'
278
- // v2 has 'subtotal' and 'tax'
279
- ```
280
-
281
- ## Example: Complete Order API
282
-
283
- ### Endpoints
284
-
285
- ```
286
- POST /orders
287
- Create order
288
- Request: CreateOrderRequest
289
- Response: 201 OrderResponse
290
-
291
- GET /orders
292
- List orders
293
- Query: ListOrdersQuery
294
- Response: 200 ListOrdersResponse
295
-
296
- GET /orders/:id
297
- Get order
298
- Response: 200 OrderResponse
299
-
300
- PATCH /orders/:id
301
- Update order
302
- Request: UpdateOrderRequest
303
- Response: 200 OrderResponse
304
-
305
- POST /orders/:id/cancel
306
- Cancel order
307
- Response: 200 OrderResponse
308
-
309
- DELETE /orders/:id
310
- Delete order
311
- Response: 204 (no body)
312
- ```
313
-
314
- ### Implementation Pattern
315
-
316
- ```typescript
317
- // Router handles HTTP concerns
318
- router.post('/orders', async (req, res) => {
319
- // 1. Parse request
320
- const request: CreateOrderRequest = req.body;
321
-
322
- // 2. Validate input (preliminary)
323
- if (!request.customerId) {
324
- return res.status(400).json({
325
- error: 'Validation failed',
326
- code: 'VALIDATION_ERROR',
327
- details: [{ field: 'customerId', message: 'Required' }]
328
- });
329
- }
330
-
331
- // 3. Call service
332
- const result = await orderService.createOrder(request);
333
-
334
- // 4. Handle result
335
- if (result.ok) {
336
- return res.status(201).json(result.value.toResponse());
337
- }
338
-
339
- // 5. Return error
340
- res.status(409).json({
341
- error: result.error,
342
- code: result.code || 'UNKNOWN_ERROR'
343
- });
344
- });
345
- ```