From the “Cascading deletes” topic of Andrea Ratto:
How to delete relations with read model? E.g. if I unsubscribe from facebook, all my facebook friends should lose me as a friend.
There a lot of options to handle this with the read model. Which one is preferred or is there another option?
Note: the Java code might not be fully correct.
Option 1 dispatch new commands in command handler:
@CommandHander
public void handle(UserUnsubscribe command) {
Collection users = userQueryRepository.getWithFriend(command.userId);
for (User user : users) {
commandBus.dispatch(new RemoveFriendCommand(user.id, command.userId));
}
User user = userRepository.load(command.userId);
user.unsubscribe();
}
Option 2 dispatch new commands in event handler:
@CommandHander
public void handle(UserUnsubscribe command) {
User user = userRepository.load(command.userId);
user.unsubscribe(); // publishes UserUnsubscribedEvent
}
@EventHandler
public void handle(UserUnsubscribedEvent event) {
Collection users = userQueryRepository.getWithFriend(event.userId);
for (User user : users) {
commandBus.dispatch(new RemoveFriendCommand(user.id, event.userId));
}
}
Option 3 only update query model:
@CommandHander
public void handle(UserUnsubscribe command) {
User user = userRepository.load(command.userId);
user.unsubscribe(); // publishes UserUnsubscribedEvent
}
@EventHandler
public void handle(UserUnsubscribedEvent event) {
Collection users = userQueryRepository.getWithFriend(event.userId);
for (User user : users) {
userQueryRepository.removeFriend(user.id, event.userId);
}
}
Option 3 doesn’t even update the other user’s aggregates.