-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathindex.ts
More file actions
54 lines (42 loc) · 1.75 KB
/
Copy pathindex.ts
File metadata and controls
54 lines (42 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import createDb from 'better-sqlite3';
import { type IContainer, ContainerBuilder, EventIdAugmentor } from '../../src/index.ts';
import { AbstractSqliteObjectProjection, SqliteEventStorage, type SqliteObjectView } from '../../src/sqlite/index.ts';
import { UserAggregate } from '../user-domain-ts/UserAggregate.ts';
import type { CreateUserCommandPayload, UserCreatedEvent, UserRecord, UserRenamedEvent } from '../user-domain-ts/messages.ts';
// -- Projection (SQLite-backed view) --
class UsersProjection extends AbstractSqliteObjectProjection<UserRecord> {
static get tableName() {
return 'users';
}
static get schemaVersion() {
return '1';
}
async userCreated(event: UserCreatedEvent) {
await this.view.updateEnforcingNew(String(event.aggregateId), () => ({
username: event.payload!.username
}));
}
async userRenamed(event: UserRenamedEvent) {
await this.view.updateEnforcingNew(String(event.aggregateId), r => ({
...r!,
username: event.payload!.username
}));
}
}
// -- Setup & Run --
interface MyContainer extends IContainer {
users: SqliteObjectView<UserRecord>;
}
const builder = new ContainerBuilder<MyContainer>();
builder.registerAggregate(UserAggregate);
builder.registerProjection(UsersProjection, 'users');
builder.register(SqliteEventStorage);
builder.register(EventIdAugmentor).as('eventIdAugmenter');
builder.registerInstance(() => createDb(':memory:'), 'viewModelSqliteDbFactory');
const { commandBus, users } = builder.container();
const [userCreated] = await commandBus.send('createUser', undefined, {
payload: { username: 'Alice', password: 'magic' } satisfies CreateUserCommandPayload
});
const userId = String(userCreated.aggregateId);
const user = await users.get(userId);
console.log('User:', user); // { username: 'Alice' }