So there is an official example here
https://github.com/kamilmysliwiec/nest-cqrs-example
and I tried to create my own for three simple features:
- Fetching all users
- Fetching one user by id
- Creating a user
I'm using TypeORM and have a basic User entity. So based on the official sample code I created a command handler for creating users ( create.user.handler.ts
):
@CommandHandler(CreateUserCommand)
export class CreateUserHandler implements ICommandHandler<CreateUserCommand> {
constructor(
private readonly usersRepository: UsersRepository,
private readonly eventPublisher: EventPublisher,
) {}
public async execute(command: CreateUserCommand): Promise<void> {
const createdUser: User = await this.usersRepository.createUser(
command.username,
command.password,
);
// const userAggregate: UserAggregate = this.eventPublisher.mergeObjectContext(
// createdUser,
// );
// userAggregate.doSomething(createdUser);
// userAggregate.commit();
}
}
All it does is persisting a new user entity to the database. But what I didn't get for now is what to do with the User aggregate. When merging the object context I can't pass in the created user entity. And further I don't know which logic should be handled by the aggregate. So based on this user aggregate ( user.model.ts
):
export class User extends AggregateRoot {
constructor(private readonly id: string) {
super();
}
public doSomething(user: UserEntity): void {
// do something here?
this.apply(new UserCreatedEvent(user));
}
}
I know that I can raise the event, that a new user was created and push it to the history. But is it the only thing it's responsible for?
So how would I setup the user aggregate and create user handler correctly?
When passing in the created entity I get an error like
Argument of type 'User' is not assignable to parameter of type 'AggregateRoot'. Type 'User' is missing the following properties from type 'AggregateRoot': autoCommit, publish, commit, uncommit, and 7 more.ts(2345)
which makes sense because the TypeORM entity extends BaseEntity
and the aggregate extends AggregateRoot
. Unforunately the official example doesn't show how to deal with aggregates AND database entities.
Update: Deleted link to temp repository, as it no longer exists.