My application needs to manage 3 types of events: creation, edit and deletion. Can I manage all these events with just one ReadSideProcessor? Is there any particular order I should prepare the statements in the prepare method?
Yes, ReadSideProcessor.defineEventHandlers accept a builder which can hold multiple events.
Since all events are unique, the order in which to define them is no important. Think about is as a hashmap(event, view-store logic)
see below,
@Override
public EventHandlers defineEventHandlers(EventHandlersBuilder builder) {
// when Account created, insert account table;
builder.setEventHandler(TransactionEvent.AccountCreatedEvent.class, (ev, offset) -> {
System.out.println("offset ->" + offset);
BoundStatement st = writeAccount.bind()
.setString("account_id", ev.id)
.setString("name", ev.name);
BoundStatement stOffset = writeOffset.bind(offset);
return completedStatements(Arrays.asList(st, stOffset));
});
// when Deposit, insert history and update balance
builder.setEventHandler(TransactionEvent.MoneyDepositedEvent.class, (ev, offset) -> {
System.out.println("offset ->" + offset);
BoundStatement historyInsert = writeHistory.bind()
.setString("account_id", ev.id)
.setLong("amount", ev.amount)
.setString("type", "DEPOSIT")
.setTimestamp("at", toTimestamp(offset));
BoundStatement accountUpdate = updateAccount.bind()
.setString("account_id", ev.id)
.setLong("balance", ev.balance + ev.amount);
return completedStatements(Arrays.asList(historyInsert, accountUpdate, writeOffset.bind(offset)));
});
// when Withdrawal, insert history and update balance
builder.setEventHandler(TransactionEvent.MoneyWithdrawnEvent.class, (ev, offset) -> {
System.out.println("offset ->" + offset);
BoundStatement historyInsert = writeHistory.bind()
.setString("account_id", ev.id)
.setLong("amount", ev.amount)
.setString("type", "WITHDRAWAL")
.setTimestamp("at", toTimestamp(offset));
BoundStatement accountUpdate = updateAccount.bind()
.setString("account_id", ev.id)
.setLong("balance", ev.balance - ev.amount);
return completedStatements(Arrays.asList(historyInsert, accountUpdate, writeOffset.bind(offset)));
});
return builder.build();
}