@zimezone/z-command 1.1.1 → 1.1.2

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 (282) hide show
  1. package/README.md +13 -1
  2. package/dist/commands/init.d.ts.map +1 -1
  3. package/dist/commands/init.js +34 -9
  4. package/dist/commands/init.js.map +1 -1
  5. package/package.json +8 -3
  6. package/templates.zip +0 -0
  7. package/templates/agents/accessibility-expert.agent.md +0 -56
  8. package/templates/agents/ai-engineer.agent.md +0 -61
  9. package/templates/agents/angular-architect.agent.md +0 -49
  10. package/templates/agents/api-designer.agent.md +0 -40
  11. package/templates/agents/api-documenter.agent.md +0 -161
  12. package/templates/agents/architect-review.agent.md +0 -146
  13. package/templates/agents/arm-cortex-expert.agent.md +0 -288
  14. package/templates/agents/azure-infra-engineer.agent.md +0 -57
  15. package/templates/agents/backend-architect.agent.md +0 -309
  16. package/templates/agents/backend-developer.agent.md +0 -61
  17. package/templates/agents/backend-security-coder.agent.md +0 -152
  18. package/templates/agents/bash-pro.agent.md +0 -285
  19. package/templates/agents/blockchain-developer.agent.md +0 -57
  20. package/templates/agents/build-engineer.agent.md +0 -56
  21. package/templates/agents/business-analyst.agent.md +0 -47
  22. package/templates/agents/c-pro.agent.md +0 -35
  23. package/templates/agents/c4-code.agent.md +0 -320
  24. package/templates/agents/c4-component.agent.md +0 -227
  25. package/templates/agents/c4-container.agent.md +0 -248
  26. package/templates/agents/c4-context.agent.md +0 -235
  27. package/templates/agents/cli-developer.agent.md +0 -57
  28. package/templates/agents/cloud-architect.agent.md +0 -56
  29. package/templates/agents/code-architect.agent.md +0 -63
  30. package/templates/agents/code-reviewer.agent.md +0 -49
  31. package/templates/agents/competitive-analyst.agent.md +0 -48
  32. package/templates/agents/conductor-validator.agent.md +0 -245
  33. package/templates/agents/context-manager.agent.md +0 -55
  34. package/templates/agents/cpp-pro.agent.md +0 -59
  35. package/templates/agents/csharp-developer.agent.md +0 -57
  36. package/templates/agents/csharp-pro.agent.md +0 -38
  37. package/templates/agents/customer-support.agent.md +0 -148
  38. package/templates/agents/data-engineer.agent.md +0 -55
  39. package/templates/agents/data-researcher.agent.md +0 -55
  40. package/templates/agents/data-scientist.agent.md +0 -56
  41. package/templates/agents/database-admin.agent.md +0 -142
  42. package/templates/agents/database-administrator.agent.md +0 -50
  43. package/templates/agents/database-architect.agent.md +0 -238
  44. package/templates/agents/database-optimizer.agent.md +0 -144
  45. package/templates/agents/debugger.agent.md +0 -30
  46. package/templates/agents/deployment-engineer.agent.md +0 -0
  47. package/templates/agents/devops-engineer.agent.md +0 -59
  48. package/templates/agents/devops-troubleshooter.agent.md +0 -138
  49. package/templates/agents/django-developer.agent.md +0 -50
  50. package/templates/agents/django-pro.agent.md +0 -159
  51. package/templates/agents/docs-architect.agent.md +0 -77
  52. package/templates/agents/documentation-engineer.agent.md +0 -57
  53. package/templates/agents/dotnet-architect.agent.md +0 -175
  54. package/templates/agents/dx-optimizer.agent.md +0 -63
  55. package/templates/agents/electron-pro.agent.md +0 -56
  56. package/templates/agents/elixir-pro.agent.md +0 -38
  57. package/templates/agents/embedded-systems.agent.md +0 -55
  58. package/templates/agents/error-detective.agent.md +0 -32
  59. package/templates/agents/event-sourcing-architect.agent.md +0 -42
  60. package/templates/agents/fastapi-pro.agent.md +0 -171
  61. package/templates/agents/fintech-engineer.agent.md +0 -57
  62. package/templates/agents/firmware-analyst.agent.md +0 -330
  63. package/templates/agents/flutter-expert.agent.md +0 -50
  64. package/templates/agents/frontend-developer.agent.md +0 -59
  65. package/templates/agents/frontend-security-coder.agent.md +0 -149
  66. package/templates/agents/fullstack-developer.agent.md +0 -46
  67. package/templates/agents/git-workflow-manager.agent.md +0 -57
  68. package/templates/agents/golang-pro.agent.md +0 -50
  69. package/templates/agents/graphql-architect.agent.md +0 -48
  70. package/templates/agents/haskell-pro.agent.md +0 -37
  71. package/templates/agents/hr-pro.agent.md +0 -105
  72. package/templates/agents/incident-responder.agent.md +0 -190
  73. package/templates/agents/ios-developer.agent.md +0 -198
  74. package/templates/agents/iot-engineer.agent.md +0 -56
  75. package/templates/agents/java-architect.agent.md +0 -48
  76. package/templates/agents/java-pro.agent.md +0 -156
  77. package/templates/agents/javascript-pro.agent.md +0 -35
  78. package/templates/agents/julia-pro.agent.md +0 -187
  79. package/templates/agents/kotlin-specialist.agent.md +0 -50
  80. package/templates/agents/laravel-specialist.agent.md +0 -50
  81. package/templates/agents/legacy-modernizer.agent.md +0 -56
  82. package/templates/agents/legal-advisor.agent.md +0 -49
  83. package/templates/agents/llm-architect.agent.md +0 -58
  84. package/templates/agents/malware-analyst.agent.md +0 -272
  85. package/templates/agents/mcp-developer.agent.md +0 -54
  86. package/templates/agents/mermaid-expert.agent.md +0 -39
  87. package/templates/agents/microservices-architect.agent.md +0 -47
  88. package/templates/agents/minecraft-bukkit-pro.agent.md +0 -104
  89. package/templates/agents/ml-engineer.agent.md +0 -56
  90. package/templates/agents/mlops-engineer.agent.md +0 -56
  91. package/templates/agents/mobile-developer.agent.md +0 -45
  92. package/templates/agents/mobile-security-coder.agent.md +0 -163
  93. package/templates/agents/monorepo-architect.agent.md +0 -44
  94. package/templates/agents/multi-agent-coordinator.agent.md +0 -55
  95. package/templates/agents/network-engineer.agent.md +0 -57
  96. package/templates/agents/nextjs-developer.agent.md +0 -48
  97. package/templates/agents/nlp-engineer.agent.md +0 -58
  98. package/templates/agents/observability-engineer.agent.md +0 -228
  99. package/templates/agents/payment-integration.agent.md +0 -56
  100. package/templates/agents/performance-engineer.agent.md +0 -167
  101. package/templates/agents/performance-optimizer.agent.md +0 -57
  102. package/templates/agents/php-pro.agent.md +0 -43
  103. package/templates/agents/platform-engineer.agent.md +0 -57
  104. package/templates/agents/posix-shell-pro.agent.md +0 -284
  105. package/templates/agents/postgres-pro.agent.md +0 -58
  106. package/templates/agents/product-manager.agent.md +0 -55
  107. package/templates/agents/project-manager.agent.md +0 -57
  108. package/templates/agents/prompt-engineer.agent.md +0 -58
  109. package/templates/agents/python-pro.agent.md +0 -48
  110. package/templates/agents/quant-analyst.agent.md +0 -32
  111. package/templates/agents/rails-expert.agent.md +0 -50
  112. package/templates/agents/react-specialist.agent.md +0 -49
  113. package/templates/agents/refactoring-specialist.agent.md +0 -56
  114. package/templates/agents/reference-builder.agent.md +0 -167
  115. package/templates/agents/research-analyst.agent.md +0 -63
  116. package/templates/agents/reverse-engineer.agent.md +0 -202
  117. package/templates/agents/risk-manager.agent.md +0 -41
  118. package/templates/agents/ruby-pro.agent.md +0 -35
  119. package/templates/agents/rust-pro.agent.md +0 -156
  120. package/templates/agents/sales-automator.agent.md +0 -35
  121. package/templates/agents/scala-pro.agent.md +0 -60
  122. package/templates/agents/scrum-master.agent.md +0 -54
  123. package/templates/agents/search-specialist.agent.md +0 -59
  124. package/templates/agents/security-analyst.agent.md +0 -57
  125. package/templates/agents/security-auditor.agent.md +0 -138
  126. package/templates/agents/security-engineer.agent.md +0 -57
  127. package/templates/agents/seo-authority-builder.agent.md +0 -116
  128. package/templates/agents/seo-cannibalization-detector.agent.md +0 -103
  129. package/templates/agents/seo-content-auditor.agent.md +0 -63
  130. package/templates/agents/seo-content-planner.agent.md +0 -88
  131. package/templates/agents/seo-content-refresher.agent.md +0 -98
  132. package/templates/agents/seo-content-writer.agent.md +0 -76
  133. package/templates/agents/seo-keyword-strategist.agent.md +0 -75
  134. package/templates/agents/seo-meta-optimizer.agent.md +0 -72
  135. package/templates/agents/seo-snippet-hunter.agent.md +0 -94
  136. package/templates/agents/seo-specialist.agent.md +0 -57
  137. package/templates/agents/seo-structure-architect.agent.md +0 -88
  138. package/templates/agents/service-mesh-expert.agent.md +0 -41
  139. package/templates/agents/sql-pro.agent.md +0 -146
  140. package/templates/agents/sre-engineer.agent.md +0 -58
  141. package/templates/agents/swift-expert.agent.md +0 -49
  142. package/templates/agents/task-distributor.agent.md +0 -47
  143. package/templates/agents/tdd-orchestrator.agent.md +0 -183
  144. package/templates/agents/technical-writer.agent.md +0 -48
  145. package/templates/agents/temporal-python-pro.agent.md +0 -349
  146. package/templates/agents/terraform-engineer.agent.md +0 -57
  147. package/templates/agents/terraform-specialist.agent.md +0 -137
  148. package/templates/agents/test-automator.agent.md +0 -203
  149. package/templates/agents/test-engineer.agent.md +0 -55
  150. package/templates/agents/threat-modeling-expert.agent.md +0 -44
  151. package/templates/agents/trend-analyst.agent.md +0 -47
  152. package/templates/agents/tutorial-engineer.agent.md +0 -118
  153. package/templates/agents/typescript-pro.agent.md +0 -48
  154. package/templates/agents/ui-designer.agent.md +0 -48
  155. package/templates/agents/ui-ux-designer.agent.md +0 -188
  156. package/templates/agents/ui-visual-validator.agent.md +0 -192
  157. package/templates/agents/ux-researcher.agent.md +0 -48
  158. package/templates/agents/vector-database-engineer.agent.md +0 -43
  159. package/templates/agents/vue-expert.agent.md +0 -48
  160. package/templates/agents/websocket-engineer.agent.md +0 -49
  161. package/templates/agents/workflow-orchestrator.agent.md +0 -48
  162. package/templates/skills/angular-migration/SKILL.md +0 -410
  163. package/templates/skills/api-design-principles/SKILL.md +0 -528
  164. package/templates/skills/api-design-principles/assets/api-design-checklist.md +0 -155
  165. package/templates/skills/api-design-principles/assets/rest-api-template.py +0 -182
  166. package/templates/skills/api-design-principles/references/graphql-schema-design.md +0 -583
  167. package/templates/skills/api-design-principles/references/rest-best-practices.md +0 -408
  168. package/templates/skills/architecture-decision-records/SKILL.md +0 -428
  169. package/templates/skills/architecture-patterns/SKILL.md +0 -494
  170. package/templates/skills/async-python-patterns/SKILL.md +0 -694
  171. package/templates/skills/auth-implementation-patterns/SKILL.md +0 -634
  172. package/templates/skills/changelog-automation/SKILL.md +0 -552
  173. package/templates/skills/code-review/SKILL.md +0 -62
  174. package/templates/skills/code-review-excellence/SKILL.md +0 -520
  175. package/templates/skills/competitive-landscape/SKILL.md +0 -479
  176. package/templates/skills/context-driven-development/SKILL.md +0 -385
  177. package/templates/skills/cost-optimization/SKILL.md +0 -274
  178. package/templates/skills/cqrs-implementation/SKILL.md +0 -554
  179. package/templates/skills/data-quality-frameworks/SKILL.md +0 -587
  180. package/templates/skills/data-storytelling/SKILL.md +0 -453
  181. package/templates/skills/database-migration/SKILL.md +0 -424
  182. package/templates/skills/dbt-transformation-patterns/SKILL.md +0 -561
  183. package/templates/skills/debugging-strategies/SKILL.md +0 -527
  184. package/templates/skills/defi-protocol-templates/SKILL.md +0 -454
  185. package/templates/skills/dependency-upgrade/SKILL.md +0 -409
  186. package/templates/skills/deployment-pipeline-design/SKILL.md +0 -359
  187. package/templates/skills/distributed-tracing/SKILL.md +0 -438
  188. package/templates/skills/dotnet-backend-patterns/SKILL.md +0 -815
  189. package/templates/skills/dotnet-backend-patterns/assets/repository-template.cs +0 -523
  190. package/templates/skills/dotnet-backend-patterns/assets/service-template.cs +0 -336
  191. package/templates/skills/dotnet-backend-patterns/references/dapper-patterns.md +0 -544
  192. package/templates/skills/dotnet-backend-patterns/references/ef-core-best-practices.md +0 -355
  193. package/templates/skills/e2e-testing-patterns/SKILL.md +0 -547
  194. package/templates/skills/employment-contract-templates/SKILL.md +0 -507
  195. package/templates/skills/error-handling-patterns/SKILL.md +0 -636
  196. package/templates/skills/event-store-design/SKILL.md +0 -437
  197. package/templates/skills/fastapi-templates/SKILL.md +0 -567
  198. package/templates/skills/git-advanced-workflows/SKILL.md +0 -400
  199. package/templates/skills/github-actions-templates/SKILL.md +0 -333
  200. package/templates/skills/go-concurrency-patterns/SKILL.md +0 -655
  201. package/templates/skills/grafana-dashboards/SKILL.md +0 -369
  202. package/templates/skills/helm-chart-scaffolding/SKILL.md +0 -544
  203. package/templates/skills/helm-chart-scaffolding/assets/Chart.yaml.template +0 -42
  204. package/templates/skills/helm-chart-scaffolding/assets/values.yaml.template +0 -185
  205. package/templates/skills/helm-chart-scaffolding/references/chart-structure.md +0 -500
  206. package/templates/skills/helm-chart-scaffolding/scripts/validate-chart.sh +0 -244
  207. package/templates/skills/javascript-testing-patterns/SKILL.md +0 -1025
  208. package/templates/skills/langchain-architecture/SKILL.md +0 -338
  209. package/templates/skills/llm-evaluation/SKILL.md +0 -471
  210. package/templates/skills/microservices-patterns/SKILL.md +0 -595
  211. package/templates/skills/modern-javascript-patterns/SKILL.md +0 -911
  212. package/templates/skills/monorepo-management/SKILL.md +0 -622
  213. package/templates/skills/nextjs-app-router-patterns/SKILL.md +0 -544
  214. package/templates/skills/nodejs-backend-patterns/SKILL.md +0 -1020
  215. package/templates/skills/nx-workspace-patterns/SKILL.md +0 -452
  216. package/templates/skills/openapi-spec-generation/SKILL.md +0 -1028
  217. package/templates/skills/paypal-integration/SKILL.md +0 -467
  218. package/templates/skills/pci-compliance/SKILL.md +0 -466
  219. package/templates/skills/postgresql/SKILL.md +0 -204
  220. package/templates/skills/projection-patterns/SKILL.md +0 -490
  221. package/templates/skills/prometheus-configuration/SKILL.md +0 -392
  222. package/templates/skills/prompt-engineering-patterns/SKILL.md +0 -201
  223. package/templates/skills/prompt-engineering-patterns/assets/few-shot-examples.json +0 -106
  224. package/templates/skills/prompt-engineering-patterns/assets/prompt-template-library.md +0 -246
  225. package/templates/skills/prompt-engineering-patterns/references/chain-of-thought.md +0 -399
  226. package/templates/skills/prompt-engineering-patterns/references/few-shot-learning.md +0 -369
  227. package/templates/skills/prompt-engineering-patterns/references/prompt-optimization.md +0 -414
  228. package/templates/skills/prompt-engineering-patterns/references/prompt-templates.md +0 -470
  229. package/templates/skills/prompt-engineering-patterns/references/system-prompts.md +0 -189
  230. package/templates/skills/prompt-engineering-patterns/scripts/optimize-prompt.py +0 -279
  231. package/templates/skills/python-packaging/SKILL.md +0 -870
  232. package/templates/skills/python-performance-optimization/SKILL.md +0 -869
  233. package/templates/skills/python-testing-patterns/SKILL.md +0 -907
  234. package/templates/skills/rag-implementation/SKILL.md +0 -403
  235. package/templates/skills/react-modernization/SKILL.md +0 -513
  236. package/templates/skills/react-native-architecture/SKILL.md +0 -671
  237. package/templates/skills/react-state-management/SKILL.md +0 -429
  238. package/templates/skills/risk-metrics-calculation/SKILL.md +0 -555
  239. package/templates/skills/rust-async-patterns/SKILL.md +0 -517
  240. package/templates/skills/secrets-management/SKILL.md +0 -346
  241. package/templates/skills/security-requirement-extraction/SKILL.md +0 -677
  242. package/templates/skills/security-review/SKILL.md +0 -78
  243. package/templates/skills/shellcheck-configuration/SKILL.md +0 -454
  244. package/templates/skills/similarity-search-patterns/SKILL.md +0 -558
  245. package/templates/skills/slo-implementation/SKILL.md +0 -329
  246. package/templates/skills/sql-optimization-patterns/SKILL.md +0 -493
  247. package/templates/skills/stripe-integration/SKILL.md +0 -442
  248. package/templates/skills/systematic-debugging/SKILL.md +0 -57
  249. package/templates/skills/tailwind-design-system/SKILL.md +0 -666
  250. package/templates/skills/temporal-python-testing/SKILL.md +0 -158
  251. package/templates/skills/temporal-python-testing/resources/integration-testing.md +0 -455
  252. package/templates/skills/temporal-python-testing/resources/local-setup.md +0 -553
  253. package/templates/skills/temporal-python-testing/resources/replay-testing.md +0 -462
  254. package/templates/skills/temporal-python-testing/resources/unit-testing.md +0 -328
  255. package/templates/skills/terraform-module-library/SKILL.md +0 -249
  256. package/templates/skills/terraform-module-library/references/aws-modules.md +0 -63
  257. package/templates/skills/test-driven-development/SKILL.md +0 -46
  258. package/templates/skills/threat-mitigation-mapping/SKILL.md +0 -745
  259. package/templates/skills/track-management/SKILL.md +0 -593
  260. package/templates/skills/typescript-advanced-types/SKILL.md +0 -717
  261. package/templates/skills/ui-ux-pro-max/SKILL.md +0 -352
  262. package/templates/skills/ui-ux-pro-max/data/charts.csv +0 -26
  263. package/templates/skills/ui-ux-pro-max/data/colors.csv +0 -97
  264. package/templates/skills/ui-ux-pro-max/data/icons.csv +0 -101
  265. package/templates/skills/ui-ux-pro-max/data/landing.csv +0 -31
  266. package/templates/skills/ui-ux-pro-max/data/products.csv +0 -97
  267. package/templates/skills/ui-ux-pro-max/data/prompts.csv +0 -24
  268. package/templates/skills/ui-ux-pro-max/data/react-performance.csv +0 -45
  269. package/templates/skills/ui-ux-pro-max/data/styles.csv +0 -59
  270. package/templates/skills/ui-ux-pro-max/data/typography.csv +0 -58
  271. package/templates/skills/ui-ux-pro-max/data/ui-reasoning.csv +0 -101
  272. package/templates/skills/ui-ux-pro-max/data/ux-guidelines.csv +0 -100
  273. package/templates/skills/ui-ux-pro-max/data/web-interface.csv +0 -31
  274. package/templates/skills/ui-ux-pro-max/scripts/core.py +0 -258
  275. package/templates/skills/ui-ux-pro-max/scripts/design_system.py +0 -547
  276. package/templates/skills/ui-ux-pro-max/scripts/search.py +0 -76
  277. package/templates/skills/uv-package-manager/SKILL.md +0 -831
  278. package/templates/skills/vector-index-tuning/SKILL.md +0 -521
  279. package/templates/skills/wcag-audit-patterns/SKILL.md +0 -555
  280. package/templates/skills/workflow-orchestration-patterns/SKILL.md +0 -316
  281. package/templates/skills/workflow-patterns/SKILL.md +0 -623
  282. package/templates/skills/writing-plans/SKILL.md +0 -64
@@ -1,554 +0,0 @@
1
- ---
2
- name: cqrs-implementation
3
- description: Implement Command Query Responsibility Segregation for scalable architectures. Use when separating read and write models, optimizing query performance, or building event-sourced systems.
4
- ---
5
-
6
- # CQRS Implementation
7
-
8
- Comprehensive guide to implementing CQRS (Command Query Responsibility Segregation) patterns.
9
-
10
- ## When to Use This Skill
11
-
12
- - Separating read and write concerns
13
- - Scaling reads independently from writes
14
- - Building event-sourced systems
15
- - Optimizing complex query scenarios
16
- - Different read/write data models needed
17
- - High-performance reporting requirements
18
-
19
- ## Core Concepts
20
-
21
- ### 1. CQRS Architecture
22
-
23
- ```
24
- ┌─────────────┐
25
- │ Client │
26
- └──────┬──────┘
27
-
28
- ┌────────────┴────────────┐
29
- │ │
30
- ▼ ▼
31
- ┌─────────────┐ ┌─────────────┐
32
- │ Commands │ │ Queries │
33
- │ API │ │ API │
34
- └──────┬──────┘ └──────┬──────┘
35
- │ │
36
- ▼ ▼
37
- ┌─────────────┐ ┌─────────────┐
38
- │ Command │ │ Query │
39
- │ Handlers │ │ Handlers │
40
- └──────┬──────┘ └──────┬──────┘
41
- │ │
42
- ▼ ▼
43
- ┌─────────────┐ ┌─────────────┐
44
- │ Write │─────────►│ Read │
45
- │ Model │ Events │ Model │
46
- └─────────────┘ └─────────────┘
47
- ```
48
-
49
- ### 2. Key Components
50
-
51
- | Component | Responsibility |
52
- | ------------------- | ------------------------------- |
53
- | **Command** | Intent to change state |
54
- | **Command Handler** | Validates and executes commands |
55
- | **Event** | Record of state change |
56
- | **Query** | Request for data |
57
- | **Query Handler** | Retrieves data from read model |
58
- | **Projector** | Updates read model from events |
59
-
60
- ## Templates
61
-
62
- ### Template 1: Command Infrastructure
63
-
64
- ```python
65
- from abc import ABC, abstractmethod
66
- from dataclasses import dataclass
67
- from typing import TypeVar, Generic, Dict, Any, Type
68
- from datetime import datetime
69
- import uuid
70
-
71
- # Command base
72
- @dataclass
73
- class Command:
74
- command_id: str = None
75
- timestamp: datetime = None
76
-
77
- def __post_init__(self):
78
- self.command_id = self.command_id or str(uuid.uuid4())
79
- self.timestamp = self.timestamp or datetime.utcnow()
80
-
81
-
82
- # Concrete commands
83
- @dataclass
84
- class CreateOrder(Command):
85
- customer_id: str
86
- items: list
87
- shipping_address: dict
88
-
89
-
90
- @dataclass
91
- class AddOrderItem(Command):
92
- order_id: str
93
- product_id: str
94
- quantity: int
95
- price: float
96
-
97
-
98
- @dataclass
99
- class CancelOrder(Command):
100
- order_id: str
101
- reason: str
102
-
103
-
104
- # Command handler base
105
- T = TypeVar('T', bound=Command)
106
-
107
- class CommandHandler(ABC, Generic[T]):
108
- @abstractmethod
109
- async def handle(self, command: T) -> Any:
110
- pass
111
-
112
-
113
- # Command bus
114
- class CommandBus:
115
- def __init__(self):
116
- self._handlers: Dict[Type[Command], CommandHandler] = {}
117
-
118
- def register(self, command_type: Type[Command], handler: CommandHandler):
119
- self._handlers[command_type] = handler
120
-
121
- async def dispatch(self, command: Command) -> Any:
122
- handler = self._handlers.get(type(command))
123
- if not handler:
124
- raise ValueError(f"No handler for {type(command).__name__}")
125
- return await handler.handle(command)
126
-
127
-
128
- # Command handler implementation
129
- class CreateOrderHandler(CommandHandler[CreateOrder]):
130
- def __init__(self, order_repository, event_store):
131
- self.order_repository = order_repository
132
- self.event_store = event_store
133
-
134
- async def handle(self, command: CreateOrder) -> str:
135
- # Validate
136
- if not command.items:
137
- raise ValueError("Order must have at least one item")
138
-
139
- # Create aggregate
140
- order = Order.create(
141
- customer_id=command.customer_id,
142
- items=command.items,
143
- shipping_address=command.shipping_address
144
- )
145
-
146
- # Persist events
147
- await self.event_store.append_events(
148
- stream_id=f"Order-{order.id}",
149
- stream_type="Order",
150
- events=order.uncommitted_events
151
- )
152
-
153
- return order.id
154
- ```
155
-
156
- ### Template 2: Query Infrastructure
157
-
158
- ```python
159
- from abc import ABC, abstractmethod
160
- from dataclasses import dataclass
161
- from typing import TypeVar, Generic, List, Optional
162
-
163
- # Query base
164
- @dataclass
165
- class Query:
166
- pass
167
-
168
-
169
- # Concrete queries
170
- @dataclass
171
- class GetOrderById(Query):
172
- order_id: str
173
-
174
-
175
- @dataclass
176
- class GetCustomerOrders(Query):
177
- customer_id: str
178
- status: Optional[str] = None
179
- page: int = 1
180
- page_size: int = 20
181
-
182
-
183
- @dataclass
184
- class SearchOrders(Query):
185
- query: str
186
- filters: dict = None
187
- sort_by: str = "created_at"
188
- sort_order: str = "desc"
189
-
190
-
191
- # Query result types
192
- @dataclass
193
- class OrderView:
194
- order_id: str
195
- customer_id: str
196
- status: str
197
- total_amount: float
198
- item_count: int
199
- created_at: datetime
200
- shipped_at: Optional[datetime] = None
201
-
202
-
203
- @dataclass
204
- class PaginatedResult(Generic[T]):
205
- items: List[T]
206
- total: int
207
- page: int
208
- page_size: int
209
-
210
- @property
211
- def total_pages(self) -> int:
212
- return (self.total + self.page_size - 1) // self.page_size
213
-
214
-
215
- # Query handler base
216
- T = TypeVar('T', bound=Query)
217
- R = TypeVar('R')
218
-
219
- class QueryHandler(ABC, Generic[T, R]):
220
- @abstractmethod
221
- async def handle(self, query: T) -> R:
222
- pass
223
-
224
-
225
- # Query bus
226
- class QueryBus:
227
- def __init__(self):
228
- self._handlers: Dict[Type[Query], QueryHandler] = {}
229
-
230
- def register(self, query_type: Type[Query], handler: QueryHandler):
231
- self._handlers[query_type] = handler
232
-
233
- async def dispatch(self, query: Query) -> Any:
234
- handler = self._handlers.get(type(query))
235
- if not handler:
236
- raise ValueError(f"No handler for {type(query).__name__}")
237
- return await handler.handle(query)
238
-
239
-
240
- # Query handler implementation
241
- class GetOrderByIdHandler(QueryHandler[GetOrderById, Optional[OrderView]]):
242
- def __init__(self, read_db):
243
- self.read_db = read_db
244
-
245
- async def handle(self, query: GetOrderById) -> Optional[OrderView]:
246
- async with self.read_db.acquire() as conn:
247
- row = await conn.fetchrow(
248
- """
249
- SELECT order_id, customer_id, status, total_amount,
250
- item_count, created_at, shipped_at
251
- FROM order_views
252
- WHERE order_id = $1
253
- """,
254
- query.order_id
255
- )
256
- if row:
257
- return OrderView(**dict(row))
258
- return None
259
-
260
-
261
- class GetCustomerOrdersHandler(QueryHandler[GetCustomerOrders, PaginatedResult[OrderView]]):
262
- def __init__(self, read_db):
263
- self.read_db = read_db
264
-
265
- async def handle(self, query: GetCustomerOrders) -> PaginatedResult[OrderView]:
266
- async with self.read_db.acquire() as conn:
267
- # Build query with optional status filter
268
- where_clause = "customer_id = $1"
269
- params = [query.customer_id]
270
-
271
- if query.status:
272
- where_clause += " AND status = $2"
273
- params.append(query.status)
274
-
275
- # Get total count
276
- total = await conn.fetchval(
277
- f"SELECT COUNT(*) FROM order_views WHERE {where_clause}",
278
- *params
279
- )
280
-
281
- # Get paginated results
282
- offset = (query.page - 1) * query.page_size
283
- rows = await conn.fetch(
284
- f"""
285
- SELECT order_id, customer_id, status, total_amount,
286
- item_count, created_at, shipped_at
287
- FROM order_views
288
- WHERE {where_clause}
289
- ORDER BY created_at DESC
290
- LIMIT ${len(params) + 1} OFFSET ${len(params) + 2}
291
- """,
292
- *params, query.page_size, offset
293
- )
294
-
295
- return PaginatedResult(
296
- items=[OrderView(**dict(row)) for row in rows],
297
- total=total,
298
- page=query.page,
299
- page_size=query.page_size
300
- )
301
- ```
302
-
303
- ### Template 3: FastAPI CQRS Application
304
-
305
- ```python
306
- from fastapi import FastAPI, HTTPException, Depends
307
- from pydantic import BaseModel
308
- from typing import List, Optional
309
-
310
- app = FastAPI()
311
-
312
- # Request/Response models
313
- class CreateOrderRequest(BaseModel):
314
- customer_id: str
315
- items: List[dict]
316
- shipping_address: dict
317
-
318
-
319
- class OrderResponse(BaseModel):
320
- order_id: str
321
- customer_id: str
322
- status: str
323
- total_amount: float
324
- item_count: int
325
- created_at: datetime
326
-
327
-
328
- # Dependency injection
329
- def get_command_bus() -> CommandBus:
330
- return app.state.command_bus
331
-
332
-
333
- def get_query_bus() -> QueryBus:
334
- return app.state.query_bus
335
-
336
-
337
- # Command endpoints (POST, PUT, DELETE)
338
- @app.post("/orders", response_model=dict)
339
- async def create_order(
340
- request: CreateOrderRequest,
341
- command_bus: CommandBus = Depends(get_command_bus)
342
- ):
343
- command = CreateOrder(
344
- customer_id=request.customer_id,
345
- items=request.items,
346
- shipping_address=request.shipping_address
347
- )
348
- order_id = await command_bus.dispatch(command)
349
- return {"order_id": order_id}
350
-
351
-
352
- @app.post("/orders/{order_id}/items")
353
- async def add_item(
354
- order_id: str,
355
- product_id: str,
356
- quantity: int,
357
- price: float,
358
- command_bus: CommandBus = Depends(get_command_bus)
359
- ):
360
- command = AddOrderItem(
361
- order_id=order_id,
362
- product_id=product_id,
363
- quantity=quantity,
364
- price=price
365
- )
366
- await command_bus.dispatch(command)
367
- return {"status": "item_added"}
368
-
369
-
370
- @app.delete("/orders/{order_id}")
371
- async def cancel_order(
372
- order_id: str,
373
- reason: str,
374
- command_bus: CommandBus = Depends(get_command_bus)
375
- ):
376
- command = CancelOrder(order_id=order_id, reason=reason)
377
- await command_bus.dispatch(command)
378
- return {"status": "cancelled"}
379
-
380
-
381
- # Query endpoints (GET)
382
- @app.get("/orders/{order_id}", response_model=OrderResponse)
383
- async def get_order(
384
- order_id: str,
385
- query_bus: QueryBus = Depends(get_query_bus)
386
- ):
387
- query = GetOrderById(order_id=order_id)
388
- result = await query_bus.dispatch(query)
389
- if not result:
390
- raise HTTPException(status_code=404, detail="Order not found")
391
- return result
392
-
393
-
394
- @app.get("/customers/{customer_id}/orders")
395
- async def get_customer_orders(
396
- customer_id: str,
397
- status: Optional[str] = None,
398
- page: int = 1,
399
- page_size: int = 20,
400
- query_bus: QueryBus = Depends(get_query_bus)
401
- ):
402
- query = GetCustomerOrders(
403
- customer_id=customer_id,
404
- status=status,
405
- page=page,
406
- page_size=page_size
407
- )
408
- return await query_bus.dispatch(query)
409
-
410
-
411
- @app.get("/orders/search")
412
- async def search_orders(
413
- q: str,
414
- sort_by: str = "created_at",
415
- query_bus: QueryBus = Depends(get_query_bus)
416
- ):
417
- query = SearchOrders(query=q, sort_by=sort_by)
418
- return await query_bus.dispatch(query)
419
- ```
420
-
421
- ### Template 4: Read Model Synchronization
422
-
423
- ```python
424
- class ReadModelSynchronizer:
425
- """Keeps read models in sync with events."""
426
-
427
- def __init__(self, event_store, read_db, projections: List[Projection]):
428
- self.event_store = event_store
429
- self.read_db = read_db
430
- self.projections = {p.name: p for p in projections}
431
-
432
- async def run(self):
433
- """Continuously sync read models."""
434
- while True:
435
- for name, projection in self.projections.items():
436
- await self._sync_projection(projection)
437
- await asyncio.sleep(0.1)
438
-
439
- async def _sync_projection(self, projection: Projection):
440
- checkpoint = await self._get_checkpoint(projection.name)
441
-
442
- events = await self.event_store.read_all(
443
- from_position=checkpoint,
444
- limit=100
445
- )
446
-
447
- for event in events:
448
- if event.event_type in projection.handles():
449
- try:
450
- await projection.apply(event)
451
- except Exception as e:
452
- # Log error, possibly retry or skip
453
- logger.error(f"Projection error: {e}")
454
- continue
455
-
456
- await self._save_checkpoint(projection.name, event.global_position)
457
-
458
- async def rebuild_projection(self, projection_name: str):
459
- """Rebuild a projection from scratch."""
460
- projection = self.projections[projection_name]
461
-
462
- # Clear existing data
463
- await projection.clear()
464
-
465
- # Reset checkpoint
466
- await self._save_checkpoint(projection_name, 0)
467
-
468
- # Rebuild
469
- while True:
470
- checkpoint = await self._get_checkpoint(projection_name)
471
- events = await self.event_store.read_all(checkpoint, 1000)
472
-
473
- if not events:
474
- break
475
-
476
- for event in events:
477
- if event.event_type in projection.handles():
478
- await projection.apply(event)
479
-
480
- await self._save_checkpoint(
481
- projection_name,
482
- events[-1].global_position
483
- )
484
- ```
485
-
486
- ### Template 5: Eventual Consistency Handling
487
-
488
- ```python
489
- class ConsistentQueryHandler:
490
- """Query handler that can wait for consistency."""
491
-
492
- def __init__(self, read_db, event_store):
493
- self.read_db = read_db
494
- self.event_store = event_store
495
-
496
- async def query_after_command(
497
- self,
498
- query: Query,
499
- expected_version: int,
500
- stream_id: str,
501
- timeout: float = 5.0
502
- ):
503
- """
504
- Execute query, ensuring read model is at expected version.
505
- Used for read-your-writes consistency.
506
- """
507
- start_time = time.time()
508
-
509
- while time.time() - start_time < timeout:
510
- # Check if read model is caught up
511
- projection_version = await self._get_projection_version(stream_id)
512
-
513
- if projection_version >= expected_version:
514
- return await self.execute_query(query)
515
-
516
- # Wait a bit and retry
517
- await asyncio.sleep(0.1)
518
-
519
- # Timeout - return stale data with warning
520
- return {
521
- "data": await self.execute_query(query),
522
- "_warning": "Data may be stale"
523
- }
524
-
525
- async def _get_projection_version(self, stream_id: str) -> int:
526
- """Get the last processed event version for a stream."""
527
- async with self.read_db.acquire() as conn:
528
- return await conn.fetchval(
529
- "SELECT last_event_version FROM projection_state WHERE stream_id = $1",
530
- stream_id
531
- ) or 0
532
- ```
533
-
534
- ## Best Practices
535
-
536
- ### Do's
537
-
538
- - **Separate command and query models** - Different needs
539
- - **Use eventual consistency** - Accept propagation delay
540
- - **Validate in command handlers** - Before state change
541
- - **Denormalize read models** - Optimize for queries
542
- - **Version your events** - For schema evolution
543
-
544
- ### Don'ts
545
-
546
- - **Don't query in commands** - Use only for writes
547
- - **Don't couple read/write schemas** - Independent evolution
548
- - **Don't over-engineer** - Start simple
549
- - **Don't ignore consistency SLAs** - Define acceptable lag
550
-
551
- ## Resources
552
-
553
- - [CQRS Pattern](https://martinfowler.com/bliki/CQRS.html)
554
- - [Microsoft CQRS Guidance](https://docs.microsoft.com/en-us/azure/architecture/patterns/cqrs)