Im new to CQRS and EventSourcing and Im sure in my first app there are a couple Anti-Patterns though I try to avoid them.
I know I shouldnt do validation in event handlers - events are facts from the past, I cant deny them. I do however small consistency checks there :
Example :
`
@SuppressWarnings("unused")
@EventSourcingHandler
protected void handle(AdminUserRoleRemovedEvent ev){
if(this.roles.contains(ev.getRole())) this.roles.remove(ev.getRole());
}
`
My question is, where does Validation and Authorization come into play?
Should I check authorization in the servers REST request handler, or in the command handler, passing the user/session context ?
There are some consistency checks that cannot be avoided in a command handler :
`
private Object handleChangeAdminUserLoginCommand(CommandMessage<ChangeAdminUserLoginCommand> commandMessage, UnitOfWork unitOfWork){
MetaData commandMetaData = MetaData.from(ImmutableMap.of("command", commandMessage));
ChangeAdminUserLoginCommand caulc = commandMessage.getPayload();
Assert.notEmpty(caulc.getNewLogin(), "Login cannot be empty");
AdminUserAggregate adminUser = eventStore.getAdminUserRepository().load(caulc.getIdentifier());
if(claimLogin(caulc.getNewLogin())){
registerUnitOfWorkListenerToCancelClaimingLogin(caulc.getNewLogin(), unitOfWork);
registerUnitOfWorkListenerToFreeClaimedLogin(adminUser.getLogin(), unitOfWork);
adminUser.changeLogin(caulc.getNewLogin(), commandMetaData);
return new AdminUser(adminUser);
} else {
throw new AdminUserLoginAlreadyTakenException(caulc.getNewLogin());
}
}
`
Also, what is the recommended way to get the aggregate identifier in event handlers ? the EventMessage class doesnt expose the ID, so for now I use a hackaround to get it. Do I really have to add an Identifier field to every event in my system ?
`
public void handleEvent(EventMessage eventMessage, BaseEvent baseEvent) {
Class<?> eventClass = eventMessage.getPayloadType();
Object aggregateIdentifier = ((GenericDomainEventMessage)eventMessage).getAggregateIdentifier(); // TODO : this is a nasty hack
`