Reputation: 1890
I'm learning to use Lagom Framework and I can't reach understanding of how the persistent side works.
My example is simple : I have a product stock and several services that create, purchase and order products, making the stock fluctuate. At the moment, I persist product with stock quantity along with each stock movement with amount added/removed. What I would like to achieve is to only persist all stock movements and create a product from them.
My understanding of Lagom Framework is that I should not persist products, but instead events of stock movements. That way, if I want to know the stock of a product, the events are processed somehow to retrieve the current state.
In my Service implementation, here is how I get a product state for now :
@Override
public ServiceCall<String, NotUsed, Source<Product, ?>> getProduct() {
return (id, req) -> {
Source<Product, ?> result = session.select("SELECT * FROM products WHERE id = ?", id)
.map(row -> new Product(row.getString("id"), row.getString("ean"), row.getLong("quantity")));
return CompletableFuture.completedFuture(result);
};
}
and here is how I add a stock :
@Override
public ServiceCall<String, Stock, NotUsed> add() {
return (id, request) -> {
log.info("EAN: {}. Supply order received.", id);
PersistentEntityRef<StockCommand> ref = persistentEntityRegistry.refFor(StockEntity.class, id);
return ref.ask(new StockCommand.AddStock(request.amount)).thenApply(r -> NotUsed.getInstance());
};
}
Is there a way with Lagom to reconstruct the product state only with persisted events ? How can it be achieved for my needs ?
Upvotes: 2
Views: 604
Reputation: 51535
My apologies, I find your example very confusing. So you have Inventory with multiple products. Each product has a count (which represents how many items are available). Order processes decrement the count as product get purchased, warehouse delivery processes increment the stock (therefore the count).
You can use the state()
function in the command to get the state.
See https://github.com/orefalo/lagom-sample-bank for more details on a similar use case.
Hope this helps,
Upvotes: 2