Skip to content

Commit

Permalink
Use checkpoint to ensure idempotency
Browse files Browse the repository at this point in the history
  • Loading branch information
lukaszreszke committed Sep 25, 2024
1 parent 8170e43 commit acb1dda
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions rails_application/app/read_models/update_product_stock_level.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,27 @@ class UpdateProductStockLevel
def call(event)
product = Product.find(event.data[:id])

case event
when Inventory::StockLevelIncreased
product.increment!(:stock_level, event.data[:quantity])
when Inventory::StockLevelDecreased
product.decrement!(:stock_level, event.data[:quantity])
checkpoint = product.checkpoint

product_stream = event_store.read.stream("Inventory::Product$#{product.id}")
product_stream = product_stream.from(checkpoint) if checkpoint

product_stream.each do |event|
case event
when Inventory::StockLevelIncreased
product.increment!(:stock_level, event.data[:quantity])
when Inventory::StockLevelDecreased
product.decrement!(:stock_level, event.data[:quantity])
end
product.checkpoint = event.event_id
end

product.save!
end

private

def event_store
Rails.configuration.event_store
end
end

0 comments on commit acb1dda

Please sign in to comment.