@celljs/cqrs 0.0.0-stage → 4.4.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 (160) hide show
  1. package/README.md +193 -2
  2. package/esm/node/aggregate/aggregate-root.d.ts +24 -0
  3. package/esm/node/aggregate/aggregate-root.js +69 -0
  4. package/esm/node/aggregate/aggregate-root.js.map +1 -0
  5. package/esm/node/aggregate/event-publisher.d.ts +16 -0
  6. package/esm/node/aggregate/event-publisher.js +42 -0
  7. package/esm/node/aggregate/event-publisher.js.map +1 -0
  8. package/esm/node/aggregate/index.d.ts +2 -0
  9. package/esm/node/aggregate/index.js +3 -0
  10. package/esm/node/aggregate/index.js.map +1 -0
  11. package/esm/node/command/command-bus.d.ts +11 -0
  12. package/esm/node/command/command-bus.js +36 -0
  13. package/esm/node/command/command-bus.js.map +1 -0
  14. package/esm/node/command/command-protocol.d.ts +30 -0
  15. package/esm/node/command/command-protocol.js +17 -0
  16. package/esm/node/command/command-protocol.js.map +1 -0
  17. package/esm/node/command/index.d.ts +2 -0
  18. package/esm/node/command/index.js +3 -0
  19. package/esm/node/command/index.js.map +1 -0
  20. package/esm/node/error/cqrs-error.d.ts +18 -0
  21. package/esm/node/error/cqrs-error.js +19 -0
  22. package/esm/node/error/cqrs-error.js.map +1 -0
  23. package/esm/node/error/index.d.ts +1 -0
  24. package/esm/node/error/index.js +2 -0
  25. package/esm/node/error/index.js.map +1 -0
  26. package/esm/node/event/event-bus.d.ts +17 -0
  27. package/esm/node/event/event-bus.js +81 -0
  28. package/esm/node/event/event-bus.js.map +1 -0
  29. package/esm/node/event/event-protocol.d.ts +42 -0
  30. package/esm/node/event/event-protocol.js +17 -0
  31. package/esm/node/event/event-protocol.js.map +1 -0
  32. package/esm/node/event/index.d.ts +3 -0
  33. package/esm/node/event/index.js +4 -0
  34. package/esm/node/event/index.js.map +1 -0
  35. package/esm/node/event/unhandled-exception-bus.d.ts +8 -0
  36. package/esm/node/event/unhandled-exception-bus.js +35 -0
  37. package/esm/node/event/unhandled-exception-bus.js.map +1 -0
  38. package/esm/node/index.d.ts +6 -0
  39. package/esm/node/index.js +7 -0
  40. package/esm/node/index.js.map +1 -0
  41. package/esm/node/module.d.ts +3 -0
  42. package/esm/node/module.js +4 -0
  43. package/esm/node/module.js.map +1 -0
  44. package/esm/node/query/index.d.ts +2 -0
  45. package/esm/node/query/index.js +3 -0
  46. package/esm/node/query/index.js.map +1 -0
  47. package/esm/node/query/query-bus.d.ts +11 -0
  48. package/esm/node/query/query-bus.js +36 -0
  49. package/esm/node/query/query-bus.js.map +1 -0
  50. package/esm/node/query/query-protocol.d.ts +31 -0
  51. package/esm/node/query/query-protocol.js +18 -0
  52. package/esm/node/query/query-protocol.js.map +1 -0
  53. package/esm/node/utils/cqrs-util.d.ts +25 -0
  54. package/esm/node/utils/cqrs-util.js +85 -0
  55. package/esm/node/utils/cqrs-util.js.map +1 -0
  56. package/esm/node/utils/index.d.ts +1 -0
  57. package/esm/node/utils/index.js +2 -0
  58. package/esm/node/utils/index.js.map +1 -0
  59. package/esm/package.json +3 -0
  60. package/lib/node/aggregate/aggregate-root.d.ts +25 -0
  61. package/lib/node/aggregate/aggregate-root.d.ts.map +1 -0
  62. package/lib/node/aggregate/aggregate-root.js +73 -0
  63. package/lib/node/aggregate/aggregate-root.js.map +1 -0
  64. package/lib/node/aggregate/event-publisher.d.ts +17 -0
  65. package/lib/node/aggregate/event-publisher.d.ts.map +1 -0
  66. package/lib/node/aggregate/event-publisher.js +45 -0
  67. package/lib/node/aggregate/event-publisher.js.map +1 -0
  68. package/lib/node/aggregate/index.d.ts +3 -0
  69. package/lib/node/aggregate/index.d.ts.map +1 -0
  70. package/lib/node/aggregate/index.js +19 -0
  71. package/lib/node/aggregate/index.js.map +1 -0
  72. package/lib/node/command/command-bus.d.ts +12 -0
  73. package/lib/node/command/command-bus.d.ts.map +1 -0
  74. package/lib/node/command/command-bus.js +39 -0
  75. package/lib/node/command/command-bus.js.map +1 -0
  76. package/lib/node/command/command-protocol.d.ts +31 -0
  77. package/lib/node/command/command-protocol.d.ts.map +1 -0
  78. package/lib/node/command/command-protocol.js +22 -0
  79. package/lib/node/command/command-protocol.js.map +1 -0
  80. package/lib/node/command/index.d.ts +3 -0
  81. package/lib/node/command/index.d.ts.map +1 -0
  82. package/lib/node/command/index.js +19 -0
  83. package/lib/node/command/index.js.map +1 -0
  84. package/lib/node/cqrs.spec.d.ts +76 -0
  85. package/lib/node/cqrs.spec.d.ts.map +1 -0
  86. package/lib/node/cqrs.spec.js +319 -0
  87. package/lib/node/cqrs.spec.js.map +1 -0
  88. package/lib/node/error/cqrs-error.d.ts +19 -0
  89. package/lib/node/error/cqrs-error.d.ts.map +1 -0
  90. package/lib/node/error/cqrs-error.js +23 -0
  91. package/lib/node/error/cqrs-error.js.map +1 -0
  92. package/lib/node/error/index.d.ts +2 -0
  93. package/lib/node/error/index.d.ts.map +1 -0
  94. package/lib/node/error/index.js +18 -0
  95. package/lib/node/error/index.js.map +1 -0
  96. package/lib/node/event/event-bus.d.ts +18 -0
  97. package/lib/node/event/event-bus.d.ts.map +1 -0
  98. package/lib/node/event/event-bus.js +84 -0
  99. package/lib/node/event/event-bus.js.map +1 -0
  100. package/lib/node/event/event-protocol.d.ts +43 -0
  101. package/lib/node/event/event-protocol.d.ts.map +1 -0
  102. package/lib/node/event/event-protocol.js +22 -0
  103. package/lib/node/event/event-protocol.js.map +1 -0
  104. package/lib/node/event/index.d.ts +4 -0
  105. package/lib/node/event/index.d.ts.map +1 -0
  106. package/lib/node/event/index.js +20 -0
  107. package/lib/node/event/index.js.map +1 -0
  108. package/lib/node/event/unhandled-exception-bus.d.ts +9 -0
  109. package/lib/node/event/unhandled-exception-bus.d.ts.map +1 -0
  110. package/lib/node/event/unhandled-exception-bus.js +38 -0
  111. package/lib/node/event/unhandled-exception-bus.js.map +1 -0
  112. package/lib/node/index.d.ts +7 -0
  113. package/lib/node/index.d.ts.map +1 -0
  114. package/lib/node/index.js +23 -0
  115. package/lib/node/index.js.map +1 -0
  116. package/lib/node/module.d.ts +4 -0
  117. package/lib/node/module.d.ts.map +1 -0
  118. package/lib/node/module.js +6 -0
  119. package/lib/node/module.js.map +1 -0
  120. package/lib/node/query/index.d.ts +3 -0
  121. package/lib/node/query/index.d.ts.map +1 -0
  122. package/lib/node/query/index.js +19 -0
  123. package/lib/node/query/index.js.map +1 -0
  124. package/lib/node/query/query-bus.d.ts +12 -0
  125. package/lib/node/query/query-bus.d.ts.map +1 -0
  126. package/lib/node/query/query-bus.js +39 -0
  127. package/lib/node/query/query-bus.js.map +1 -0
  128. package/lib/node/query/query-protocol.d.ts +32 -0
  129. package/lib/node/query/query-protocol.d.ts.map +1 -0
  130. package/lib/node/query/query-protocol.js +23 -0
  131. package/lib/node/query/query-protocol.js.map +1 -0
  132. package/lib/node/utils/cqrs-util.d.ts +26 -0
  133. package/lib/node/utils/cqrs-util.d.ts.map +1 -0
  134. package/lib/node/utils/cqrs-util.js +88 -0
  135. package/lib/node/utils/cqrs-util.js.map +1 -0
  136. package/lib/node/utils/index.d.ts +2 -0
  137. package/lib/node/utils/index.d.ts.map +1 -0
  138. package/lib/node/utils/index.js +18 -0
  139. package/lib/node/utils/index.js.map +1 -0
  140. package/package.json +88 -4
  141. package/src/node/aggregate/aggregate-root.ts +78 -0
  142. package/src/node/aggregate/event-publisher.ts +43 -0
  143. package/src/node/aggregate/index.ts +2 -0
  144. package/src/node/command/command-bus.ts +28 -0
  145. package/src/node/command/command-protocol.ts +39 -0
  146. package/src/node/command/index.ts +2 -0
  147. package/src/node/cqrs.spec.ts +316 -0
  148. package/src/node/error/cqrs-error.ts +23 -0
  149. package/src/node/error/index.ts +1 -0
  150. package/src/node/event/event-bus.ts +70 -0
  151. package/src/node/event/event-protocol.ts +60 -0
  152. package/src/node/event/index.ts +3 -0
  153. package/src/node/event/unhandled-exception-bus.ts +21 -0
  154. package/src/node/index.ts +6 -0
  155. package/src/node/module.ts +4 -0
  156. package/src/node/query/index.ts +2 -0
  157. package/src/node/query/query-bus.ts +28 -0
  158. package/src/node/query/query-protocol.ts +40 -0
  159. package/src/node/utils/cqrs-util.ts +90 -0
  160. package/src/node/utils/index.ts +1 -0
@@ -0,0 +1,316 @@
1
+ import { beforeAll, describe, expect, it } from 'bun:test';
2
+ import { Autowired, autoBind, Container } from '@celljs/core';
3
+ import { coreTestModule } from '@celljs/core/lib/common/test/test-module';
4
+ import {
5
+ AggregateRoot,
6
+ CommandBus,
7
+ CommandHandler,
8
+ CommandMessage,
9
+ CqrsError,
10
+ EventBus,
11
+ EventHandler,
12
+ EventPublisher,
13
+ QueryBus,
14
+ QueryHandler,
15
+ QueryMessage,
16
+ Saga,
17
+ type UnhandledException,
18
+ UnhandledExceptionBus,
19
+ } from './index';
20
+ import cqrsModule from './module';
21
+
22
+ class CreateAccount extends CommandMessage<string> {
23
+ constructor(
24
+ readonly owner: string,
25
+ readonly balance = 0,
26
+ ) {
27
+ super();
28
+ }
29
+ }
30
+
31
+ class Deposit {
32
+ constructor(
33
+ readonly id: string,
34
+ readonly amount: number,
35
+ ) {}
36
+ }
37
+
38
+ class SendWelcome {
39
+ constructor(readonly owner: string) {}
40
+ }
41
+
42
+ class GetAccount extends QueryMessage<Account | undefined> {
43
+ constructor(readonly id: string) {
44
+ super();
45
+ }
46
+ }
47
+
48
+ class Unhandled {}
49
+
50
+ class AccountCreated {
51
+ constructor(
52
+ readonly id: string,
53
+ readonly owner: string,
54
+ readonly balance: number,
55
+ ) {}
56
+ }
57
+
58
+ class MoneyDeposited {
59
+ constructor(
60
+ readonly id: string,
61
+ readonly amount: number,
62
+ ) {}
63
+ }
64
+
65
+ class Failing {}
66
+
67
+ class Account extends AggregateRoot {
68
+ owner: string;
69
+ balance = 0;
70
+
71
+ constructor(readonly id: string) {
72
+ super();
73
+ }
74
+
75
+ open(owner: string, balance: number): void {
76
+ this.apply(new AccountCreated(this.id, owner, balance));
77
+ }
78
+
79
+ deposit(amount: number): void {
80
+ this.apply(new MoneyDeposited(this.id, amount));
81
+ }
82
+
83
+ onAccountCreated(event: AccountCreated): void {
84
+ this.owner = event.owner;
85
+ this.balance = event.balance;
86
+ }
87
+
88
+ onMoneyDeposited(event: MoneyDeposited): void {
89
+ this.balance += event.amount;
90
+ }
91
+ }
92
+
93
+ const log: string[] = [];
94
+ const store = new Map<string, Account>();
95
+
96
+ @CommandHandler(CreateAccount)
97
+ export class CreateAccountHandler implements CommandHandler<CreateAccount> {
98
+ @Autowired(EventPublisher)
99
+ protected readonly publisher: EventPublisher;
100
+
101
+ async execute(command: CreateAccount): Promise<string> {
102
+ const account = this.publisher.mergeObjectContext(new Account(`a${store.size + 1}`));
103
+ account.open(command.owner, command.balance);
104
+ store.set(account.id, account);
105
+ await account.commit();
106
+ return account.id;
107
+ }
108
+ }
109
+
110
+ @CommandHandler(Deposit)
111
+ export class DepositHandler implements CommandHandler<Deposit> {
112
+ @Autowired(EventPublisher)
113
+ protected readonly publisher: EventPublisher;
114
+
115
+ async execute(command: Deposit): Promise<void> {
116
+ const account = store.get(command.id) as Account;
117
+ this.publisher.mergeObjectContext(account);
118
+ account.deposit(command.amount);
119
+ await account.commit();
120
+ }
121
+ }
122
+
123
+ @CommandHandler(SendWelcome)
124
+ export class SendWelcomeHandler implements CommandHandler<SendWelcome> {
125
+ execute(command: SendWelcome): void {
126
+ log.push(`welcome ${command.owner}`);
127
+ }
128
+ }
129
+
130
+ @QueryHandler(GetAccount)
131
+ export class GetAccountHandler implements QueryHandler<GetAccount> {
132
+ execute(query: GetAccount): Account | undefined {
133
+ return store.get(query.id);
134
+ }
135
+ }
136
+
137
+ @EventHandler(AccountCreated)
138
+ export class AuditHandler implements EventHandler<AccountCreated> {
139
+ async handle(event: AccountCreated): Promise<void> {
140
+ await new Promise(resolve => setTimeout(resolve, 5));
141
+ log.push(`audit ${event.id}`);
142
+ }
143
+ }
144
+
145
+ @EventHandler([AccountCreated, MoneyDeposited])
146
+ export class ProjectionHandler implements EventHandler<AccountCreated | MoneyDeposited> {
147
+ @Autowired(QueryBus)
148
+ protected readonly queryBus: QueryBus;
149
+
150
+ async handle(event: AccountCreated | MoneyDeposited): Promise<void> {
151
+ const account = await this.queryBus.execute(new GetAccount(event.id));
152
+ log.push(`projection ${event.constructor.name} ${account?.balance}`);
153
+ }
154
+ }
155
+
156
+ @EventHandler(Failing)
157
+ export class FailingHandler implements EventHandler<Failing> {
158
+ handle(): void {
159
+ throw new Error('boom');
160
+ }
161
+ }
162
+
163
+ @EventHandler(Failing)
164
+ export class OtherFailingHandler implements EventHandler<Failing> {
165
+ handle(): void {
166
+ log.push('other handler of Failing');
167
+ }
168
+ }
169
+
170
+ @Saga(AccountCreated)
171
+ export class WelcomeSaga implements Saga<AccountCreated> {
172
+ handle(event: AccountCreated): SendWelcome {
173
+ return new SendWelcome(event.owner);
174
+ }
175
+ }
176
+
177
+ /** Type checks only: the result types come from CommandMessage and QueryMessage. */
178
+ export async function typedResults(commandBus: CommandBus, queryBus: QueryBus): Promise<void> {
179
+ const id: string = await commandBus.execute(new CreateAccount('dave'));
180
+ const account: Account | undefined = await queryBus.execute(new GetAccount(id));
181
+ // @ts-expect-error the result of CreateAccount is a string
182
+ const wrong: number = await commandBus.execute(new CreateAccount('dave'));
183
+ const untyped: number = await commandBus.execute<number>(new Deposit(id, 1));
184
+ console.log(account, wrong, untyped);
185
+ }
186
+
187
+ describe('@celljs/cqrs', () => {
188
+ let container: Container;
189
+ let commandBus: CommandBus;
190
+ let queryBus: QueryBus;
191
+ let eventBus: EventBus;
192
+
193
+ beforeAll(() => {
194
+ container = new Container(coreTestModule, cqrsModule, autoBind());
195
+ commandBus = container.get<CommandBus>(CommandBus);
196
+ queryBus = container.get<QueryBus>(QueryBus);
197
+ eventBus = container.get<EventBus>(EventBus);
198
+ });
199
+
200
+ it('runs a command with its handler, publishes the events of the aggregate and waits for their handlers and sagas', async () => {
201
+ log.length = 0;
202
+ const id: string = await commandBus.execute(new CreateAccount('alice', 10));
203
+ expect(id).toBe('a1');
204
+ expect(log.sort()).toEqual(['audit a1', 'projection AccountCreated 10', 'welcome alice']);
205
+ });
206
+
207
+ it('answers a query with its handler, typed by QueryMessage', async () => {
208
+ await commandBus.execute(new Deposit('a1', 5));
209
+ const account = await queryBus.execute(new GetAccount('a1'));
210
+ expect(account?.balance).toBe(15);
211
+ expect(account?.getUncommittedEvents()).toEqual([]);
212
+ });
213
+
214
+ it('rejects a command or query without a handler with CELL_CQRS_NO_HANDLER', async () => {
215
+ const error = await commandBus.execute(new Unhandled()).catch(e => e);
216
+ expect(CqrsError.is(error, 'CELL_CQRS_NO_HANDLER')).toBe(true);
217
+ expect(error.message).toBe('No handler for the command Unhandled.');
218
+ expect(error.hint).toContain('@CommandHandler(Unhandled)');
219
+ const queryError = await queryBus.execute(new Unhandled()).catch(e => e);
220
+ expect(queryError.hint).toContain('@QueryHandler(Unhandled)');
221
+ });
222
+
223
+ it('rejects messages that are not instances of a class with CELL_CQRS_NOT_AN_INSTANCE', async () => {
224
+ for (const message of [{ owner: 'bob' }, undefined, 'x']) {
225
+ const error = await commandBus.execute(message as object).catch(e => e);
226
+ expect(CqrsError.is(error, 'CELL_CQRS_NOT_AN_INSTANCE')).toBe(true);
227
+ }
228
+ const error = await eventBus.publish({}).catch(e => e);
229
+ expect(error.message).toBe('An event must be an instance of a class, got a plain object.');
230
+ });
231
+
232
+ it('hands what an event handler throws to the UnhandledExceptionBus without failing the publisher or the other handlers', async () => {
233
+ log.length = 0;
234
+ const exceptions: UnhandledException[] = [];
235
+ const subscription = container.get<UnhandledExceptionBus>(UnhandledExceptionBus).onException(e => exceptions.push(e));
236
+ const event = new Failing();
237
+ await eventBus.publish(event);
238
+ subscription.dispose();
239
+ expect(log).toEqual(['other handler of Failing']);
240
+ expect(exceptions.length).toBe(1);
241
+ expect((exceptions[0].error as Error).message).toBe('boom');
242
+ expect(exceptions[0].event).toBe(event);
243
+ expect(exceptions[0].handler).toBeInstanceOf(FailingHandler);
244
+ });
245
+
246
+ it('publishes events without handlers and publishAll keeps the order', async () => {
247
+ log.length = 0;
248
+ await eventBus.publish(new Unhandled());
249
+ await eventBus.publishAll([new MoneyDeposited('a1', 0), new Failing()]);
250
+ expect(log).toEqual(['projection MoneyDeposited 15', 'other handler of Failing']);
251
+ });
252
+
253
+ it('rejects a second handler of a command with CELL_CQRS_DUPLICATE_HANDLER', async () => {
254
+ class Twice {}
255
+ @CommandHandler(Twice)
256
+ class First {
257
+ execute(): void {}
258
+ }
259
+ @CommandHandler(Twice)
260
+ class Second {
261
+ execute(): void {}
262
+ }
263
+ expect([First.name, Second.name]).toEqual(['First', 'Second']);
264
+ const other = new Container(coreTestModule, cqrsModule, autoBind());
265
+ const error = await other
266
+ .get<CommandBus>(CommandBus)
267
+ .execute(new Twice())
268
+ .catch(e => e);
269
+ expect(CqrsError.is(error, 'CELL_CQRS_DUPLICATE_HANDLER')).toBe(true);
270
+ expect(error.message).toBe('The command Twice has 2 handlers: First, Second.');
271
+ });
272
+ });
273
+
274
+ describe('AggregateRoot', () => {
275
+ it('applies events with on<EventClassName>, records them and rebuilds from history without recording', () => {
276
+ const account = new Account('x');
277
+ account.open('carol', 1);
278
+ account.deposit(2);
279
+ expect(account.balance).toBe(3);
280
+ expect(account.getUncommittedEvents().map(e => e.constructor.name)).toEqual(['AccountCreated', 'MoneyDeposited']);
281
+ account.uncommit();
282
+ expect(account.getUncommittedEvents()).toEqual([]);
283
+
284
+ const replayed = new Account('x');
285
+ replayed.loadFromHistory([new AccountCreated('x', 'carol', 1), new MoneyDeposited('x', 2)]);
286
+ expect(replayed.balance).toBe(3);
287
+ expect(replayed.getUncommittedEvents()).toEqual([]);
288
+ expect(JSON.stringify(replayed)).toBe('{"id":"x","balance":3,"owner":"carol"}');
289
+ });
290
+
291
+ it('rejects commit() with CELL_CQRS_AGGREGATE_NOT_MERGED and keeps the events when it is not connected', async () => {
292
+ const account = new Account('y');
293
+ account.deposit(1);
294
+ const error = await account.commit().catch(e => e);
295
+ expect(CqrsError.is(error, 'CELL_CQRS_AGGREGATE_NOT_MERGED')).toBe(true);
296
+ expect(error.message).toBe('Account cannot publish MoneyDeposited: it is not connected to the event bus.');
297
+ expect(account.getUncommittedEvents().length).toBe(1);
298
+ });
299
+
300
+ it('mergeClassContext gives a subclass whose instances publish to the event bus', async () => {
301
+ const container = new Container(coreTestModule, cqrsModule);
302
+ const published: object[] = [];
303
+ const eventBus = container.get<EventBus>(EventBus);
304
+ eventBus.publishAll = async events => {
305
+ published.push(...events);
306
+ };
307
+ const MergedAccount = container.get<EventPublisher>(EventPublisher).mergeClassContext(Account);
308
+ const account = new MergedAccount('z');
309
+ account.deposit(4);
310
+ await account.commit();
311
+ expect(MergedAccount.name).toBe('Account');
312
+ expect(account).toBeInstanceOf(Account);
313
+ expect(published.length).toBe(1);
314
+ expect(account.getUncommittedEvents()).toEqual([]);
315
+ });
316
+ });
@@ -0,0 +1,23 @@
1
+ /**
2
+ * A command, query or event that cannot be dispatched. `code` is stable and `hint` says how to fix it
3
+ * in one sentence (docs/design/agent-first.md R5).
4
+ */
5
+ export class CqrsError extends Error {
6
+ override readonly name = 'CqrsError';
7
+ readonly code: CqrsError.Code;
8
+ readonly hint: string;
9
+
10
+ constructor(options: { code: CqrsError.Code; message: string; hint: string }) {
11
+ super(options.message);
12
+ this.code = options.code;
13
+ this.hint = options.hint;
14
+ }
15
+ }
16
+
17
+ export namespace CqrsError {
18
+ export type Code = 'CELL_CQRS_NOT_AN_INSTANCE' | 'CELL_CQRS_NO_HANDLER' | 'CELL_CQRS_DUPLICATE_HANDLER' | 'CELL_CQRS_AGGREGATE_NOT_MERGED';
19
+
20
+ export function is(error: unknown, code?: Code): error is CqrsError {
21
+ return error instanceof CqrsError && (code === undefined || error.code === code);
22
+ }
23
+ }
@@ -0,0 +1 @@
1
+ export * from './cqrs-error';
@@ -0,0 +1,70 @@
1
+ import { Autowired, AutowiredProvider, Component, type Provider } from '@celljs/core';
2
+ import { CommandBus } from '../command/command-protocol';
3
+ import { CqrsUtil, METADATA_KEY, type MessageType } from '../utils';
4
+ import { EVENT_HANDLER, EventBus, type EventHandler, SAGA, type Saga, UnhandledExceptionBus } from './event-protocol';
5
+
6
+ const NONE: readonly never[] = [];
7
+
8
+ @Component(EventBus)
9
+ export class EventBusImpl implements EventBus {
10
+ /** Providers: the handlers and sagas are created when the first event is published, so they can inject the buses. */
11
+ @AutowiredProvider(EVENT_HANDLER)
12
+ protected readonly handlerProvider: Provider<EventHandler>;
13
+
14
+ @AutowiredProvider(SAGA)
15
+ protected readonly sagaProvider: Provider<Saga>;
16
+
17
+ @Autowired(CommandBus)
18
+ protected readonly commandBus: CommandBus;
19
+
20
+ @Autowired(UnhandledExceptionBus)
21
+ protected readonly unhandledExceptionBus: UnhandledExceptionBus;
22
+
23
+ protected handlers?: Map<MessageType, EventHandler[]>;
24
+ protected sagas?: Map<MessageType, Saga[]>;
25
+
26
+ async publish(event: object): Promise<void> {
27
+ const type = CqrsUtil.typeOf(event, 'event');
28
+ this.handlers ??= CqrsUtil.index(this.handlerProvider.get(), METADATA_KEY.eventHandler);
29
+ this.sagas ??= CqrsUtil.index(this.sagaProvider.get(), METADATA_KEY.saga);
30
+ const handlers = this.handlers.get(type) ?? NONE;
31
+ const sagas = this.sagas.get(type) ?? NONE;
32
+ if (handlers.length === 1 && sagas.length === 0) {
33
+ return this.handle(handlers[0], event);
34
+ }
35
+ const tasks: Promise<void>[] = [];
36
+ for (const handler of handlers) {
37
+ tasks.push(this.handle(handler, event));
38
+ }
39
+ for (const saga of sagas) {
40
+ tasks.push(this.runSaga(saga, event));
41
+ }
42
+ await Promise.all(tasks);
43
+ }
44
+
45
+ async publishAll(events: object[]): Promise<void> {
46
+ for (const event of events) {
47
+ await this.publish(event);
48
+ }
49
+ }
50
+
51
+ protected async handle(handler: EventHandler, event: object): Promise<void> {
52
+ try {
53
+ await handler.handle(event);
54
+ } catch (error) {
55
+ this.unhandledExceptionBus.publish({ error, event, handler });
56
+ }
57
+ }
58
+
59
+ protected async runSaga(saga: Saga, event: object): Promise<void> {
60
+ try {
61
+ const result = await saga.handle(event);
62
+ const commands = result === undefined || result === null ? NONE : Array.isArray(result) ? result : [result];
63
+ for (const command of commands) {
64
+ await this.commandBus.execute(command);
65
+ }
66
+ } catch (error) {
67
+ this.unhandledExceptionBus.publish({ error, event, handler: saga });
68
+ }
69
+ }
70
+ }
@@ -0,0 +1,60 @@
1
+ import type { ComponentOption, Event, MaybePromise, Newable } from '@celljs/core';
2
+ import { CqrsUtil, METADATA_KEY } from '../utils';
3
+
4
+ export const EventBus = Symbol('EventBus');
5
+ export const UnhandledExceptionBus = Symbol('UnhandledExceptionBus');
6
+ export const EVENT_HANDLER = Symbol('EventHandler');
7
+ export const SAGA = Symbol('Saga');
8
+
9
+ /** Reacts to events that happened; an event class can have any number of handlers. */
10
+ export interface EventHandler<E extends object = any> {
11
+ handle(event: E): MaybePromise<void>;
12
+ }
13
+
14
+ /** Makes the class a component that handles the events of the given classes. */
15
+ export function EventHandler(events: Newable<object> | Newable<object>[], option?: ComponentOption): ClassDecorator {
16
+ return target => CqrsUtil.applyHandlerDecorator(target, EVENT_HANDLER, METADATA_KEY.eventHandler, toArray(events), option);
17
+ }
18
+
19
+ /**
20
+ * Turns an event into the commands that follow from it: the event bus runs what `handle` returns
21
+ * (a command, an array of commands or nothing) with the command bus, in order.
22
+ */
23
+ export interface Saga<E extends object = any> {
24
+ // biome-ignore lint/suspicious/noConfusingVoidType: a saga that returns nothing dispatches no command
25
+ handle(event: E): MaybePromise<object | object[] | undefined | void>;
26
+ }
27
+
28
+ /** Makes the class a component that turns the events of the given classes into commands. */
29
+ export function Saga(events: Newable<object> | Newable<object>[], option?: ComponentOption): ClassDecorator {
30
+ return target => CqrsUtil.applyHandlerDecorator(target, SAGA, METADATA_KEY.saga, toArray(events), option);
31
+ }
32
+
33
+ /** Hands events to their handlers and sagas. */
34
+ export interface EventBus {
35
+ /**
36
+ * Runs the handlers and sagas of the event concurrently and resolves when they are all done.
37
+ * What they throw does not reject it: it goes to the `UnhandledExceptionBus`.
38
+ * Rejects with a `CqrsError` when the event is not an instance of a class.
39
+ */
40
+ publish(event: object): Promise<void>;
41
+ /** Publishes the events one after the other. */
42
+ publishAll(events: object[]): Promise<void>;
43
+ }
44
+
45
+ /** What an event handler or a saga (`handler`) threw while handling `event`. */
46
+ export interface UnhandledException {
47
+ error: unknown;
48
+ event: object;
49
+ handler: object;
50
+ }
51
+
52
+ /** Where the errors of event handlers and sagas go; they are logged too. */
53
+ export interface UnhandledExceptionBus {
54
+ readonly onException: Event<UnhandledException>;
55
+ publish(exception: UnhandledException): void;
56
+ }
57
+
58
+ function toArray<T>(value: T | T[]): T[] {
59
+ return Array.isArray(value) ? value : [value];
60
+ }
@@ -0,0 +1,3 @@
1
+ export * from './event-bus';
2
+ export * from './event-protocol';
3
+ export * from './unhandled-exception-bus';
@@ -0,0 +1,21 @@
1
+ import { Autowired, Component, Emitter, getTargetClass, Logger } from '@celljs/core';
2
+ import { type UnhandledException, UnhandledExceptionBus } from './event-protocol';
3
+
4
+ @Component(UnhandledExceptionBus)
5
+ export class UnhandledExceptionBusImpl implements UnhandledExceptionBus {
6
+ @Autowired(Logger)
7
+ protected readonly logger: Logger;
8
+
9
+ protected readonly onExceptionEmitter = new Emitter<UnhandledException>();
10
+
11
+ get onException() {
12
+ return this.onExceptionEmitter.event;
13
+ }
14
+
15
+ publish(exception: UnhandledException): void {
16
+ const { error, event, handler } = exception;
17
+ const reason = error instanceof Error ? (error.stack ?? error.message) : String(error);
18
+ this.logger.error(`${getTargetClass(handler).name} failed on the event ${event.constructor.name}: ${reason}`);
19
+ this.onExceptionEmitter.fire(exception);
20
+ }
21
+ }
@@ -0,0 +1,6 @@
1
+ export * from './aggregate';
2
+ export * from './command';
3
+ export * from './error';
4
+ export * from './event';
5
+ export * from './query';
6
+ export * from './utils';
@@ -0,0 +1,4 @@
1
+ import { autoBind } from '@celljs/core';
2
+ import './index';
3
+
4
+ export default autoBind();
@@ -0,0 +1,2 @@
1
+ export * from './query-bus';
2
+ export * from './query-protocol';
@@ -0,0 +1,28 @@
1
+ import { AutowiredProvider, Component, type Provider } from '@celljs/core';
2
+ import { CqrsUtil, METADATA_KEY, type MessageType } from '../utils';
3
+ import { QUERY_HANDLER, QueryBus, type QueryHandler, type QueryMessage } from './query-protocol';
4
+
5
+ @Component(QueryBus)
6
+ export class QueryBusImpl implements QueryBus {
7
+ /** A provider: the handlers are created when the first query runs, so they can inject the buses. */
8
+ @AutowiredProvider(QUERY_HANDLER)
9
+ protected readonly handlerProvider: Provider<QueryHandler>;
10
+
11
+ protected handlers?: Map<MessageType, QueryHandler>;
12
+
13
+ execute<R>(query: QueryMessage<R>): Promise<R>;
14
+ execute<R = any>(query: object): Promise<R>;
15
+ async execute(query: object): Promise<any> {
16
+ return this.getHandler(query).execute(query);
17
+ }
18
+
19
+ protected getHandler(query: object): QueryHandler {
20
+ const type = CqrsUtil.typeOf(query, 'query');
21
+ this.handlers ??= CqrsUtil.single(this.handlerProvider.get(), METADATA_KEY.queryHandler, 'query');
22
+ const handler = this.handlers.get(type);
23
+ if (!handler) {
24
+ throw CqrsUtil.noHandler(type, 'query');
25
+ }
26
+ return handler;
27
+ }
28
+ }
@@ -0,0 +1,40 @@
1
+ import type { ComponentOption, MaybePromise, Newable } from '@celljs/core';
2
+ import { CqrsUtil, METADATA_KEY } from '../utils';
3
+
4
+ export const QueryBus = Symbol('QueryBus');
5
+ export const QUERY_HANDLER = Symbol('QueryHandler');
6
+
7
+ /**
8
+ * Optional base class of a query that gives `QueryBus.execute` its result type:
9
+ * `class GetUser extends QueryMessage<User> { ... }` makes `execute(new GetUser(...))` a `Promise<User>`.
10
+ * (Not named `Query`: `@celljs/mvc` has a `@Query` parameter decorator.)
11
+ */
12
+ export abstract class QueryMessage<R = any> {
13
+ /** Carries the result type only; never set. */
14
+ declare readonly __result: R;
15
+ }
16
+
17
+ export type QueryResult<Q> = Q extends QueryMessage<infer R> ? R : any;
18
+
19
+ /** Reads the state of the application without changing it; the one handler of a query class is selected by the class of the query. */
20
+ export interface QueryHandler<Q extends object = any, R = QueryResult<Q>> {
21
+ execute(query: Q): MaybePromise<R>;
22
+ }
23
+
24
+ /**
25
+ * Makes the class a component that answers the queries of the given class.
26
+ * Each query class has exactly one handler.
27
+ */
28
+ export function QueryHandler(query: Newable<object>, option?: ComponentOption): ClassDecorator {
29
+ return target => CqrsUtil.applyHandlerDecorator(target, QUERY_HANDLER, METADATA_KEY.queryHandler, [query], option);
30
+ }
31
+
32
+ /** Answers a query with its handler. */
33
+ export interface QueryBus {
34
+ /**
35
+ * Runs the handler of the query and resolves to what it returns.
36
+ * Rejects with what the handler throws, or a `CqrsError` when no handler handles the query.
37
+ */
38
+ execute<R>(query: QueryMessage<R>): Promise<R>;
39
+ execute<R = any>(query: object): Promise<R>;
40
+ }
@@ -0,0 +1,90 @@
1
+ import { Component, type ComponentId, type ComponentOption, getTargetClass, parseComponentOption } from '@celljs/core';
2
+ import { CqrsError } from '../error';
3
+
4
+ export type MessageKind = 'command' | 'query' | 'event';
5
+
6
+ /** The class of a command, query or event. */
7
+ export type MessageType = new (...args: any[]) => object;
8
+
9
+ export const METADATA_KEY = {
10
+ commandHandler: 'cell:cqrs:command-handler',
11
+ queryHandler: 'cell:cqrs:query-handler',
12
+ eventHandler: 'cell:cqrs:event-handler',
13
+ saga: 'cell:cqrs:saga',
14
+ };
15
+
16
+ const DECORATOR: Record<MessageKind, string> = { command: '@CommandHandler', query: '@QueryHandler', event: '@EventHandler' };
17
+
18
+ export namespace CqrsUtil {
19
+ /**
20
+ * Registers the class as a component that is also bound to `id` and records the message classes it handles,
21
+ * for the bus that collects the components of `id`.
22
+ */
23
+ export function applyHandlerDecorator(target: any, id: ComponentId, metadataKey: string, types: MessageType[], option?: ComponentOption): void {
24
+ const parsed = parseComponentOption(target, option);
25
+ (parsed.id as ComponentId[]).push(id);
26
+ Reflect.defineMetadata(metadataKey, types, target);
27
+ Component(parsed)(target);
28
+ }
29
+
30
+ /** The class of a command, query or event: what selects its handlers. */
31
+ export function typeOf(message: unknown, kind: MessageKind): MessageType {
32
+ const type = message !== null && typeof message === 'object' ? message.constructor : undefined;
33
+ if (typeof type !== 'function' || type === Object) {
34
+ throw new CqrsError({
35
+ code: 'CELL_CQRS_NOT_AN_INSTANCE',
36
+ message: `${kind === 'event' ? 'An' : 'A'} ${kind} must be an instance of a class, got ${describe(message)}.`,
37
+ hint: `Declare a class for the ${kind}, dispatch new MyClass(...) and decorate its handler with ${DECORATOR[kind]}(MyClass).`,
38
+ });
39
+ }
40
+ return type as MessageType;
41
+ }
42
+
43
+ /** The handlers by the message class they handle, in the order the container gives them. */
44
+ export function index<H extends object>(handlers: H[], metadataKey: string): Map<MessageType, H[]> {
45
+ const result = new Map<MessageType, H[]>();
46
+ for (const handler of handlers) {
47
+ const types: MessageType[] = Reflect.getOwnMetadata(metadataKey, getTargetClass(handler)) || [];
48
+ for (const type of types) {
49
+ const list = result.get(type);
50
+ if (list) {
51
+ list.push(handler);
52
+ } else {
53
+ result.set(type, [handler]);
54
+ }
55
+ }
56
+ }
57
+ return result;
58
+ }
59
+
60
+ /** The one handler of each message class; commands and queries have exactly one. */
61
+ export function single<H extends object>(handlers: H[], metadataKey: string, kind: MessageKind): Map<MessageType, H> {
62
+ const result = new Map<MessageType, H>();
63
+ for (const [type, list] of index(handlers, metadataKey)) {
64
+ if (list.length > 1) {
65
+ throw new CqrsError({
66
+ code: 'CELL_CQRS_DUPLICATE_HANDLER',
67
+ message: `The ${kind} ${type.name} has ${list.length} handlers: ${list.map(h => getTargetClass(h).name).join(', ')}.`,
68
+ hint: `Keep one ${DECORATOR[kind]}(${type.name}) class; to react to something in several places, publish an event.`,
69
+ });
70
+ }
71
+ result.set(type, list[0]);
72
+ }
73
+ return result;
74
+ }
75
+
76
+ export function noHandler(type: MessageType, kind: MessageKind): CqrsError {
77
+ return new CqrsError({
78
+ code: 'CELL_CQRS_NO_HANDLER',
79
+ message: `No handler for the ${kind} ${type.name}.`,
80
+ hint: `Decorate a class with ${DECORATOR[kind]}(${type.name}) in a file that the DI module of your application imports.`,
81
+ });
82
+ }
83
+
84
+ function describe(value: unknown): string {
85
+ if (value === null || value === undefined) {
86
+ return String(value);
87
+ }
88
+ return typeof value === 'object' ? 'a plain object' : `a ${typeof value}`;
89
+ }
90
+ }
@@ -0,0 +1 @@
1
+ export * from './cqrs-util';