Blog>
Snippets

Using Event Sourcing for State Management in Sagas

Show how to use event sourcing for state management in a saga pattern for an order management system, tracking events like order created, payment received, and shipment initiated.
class OrderEvents {
  constructor() {
    this.events = [];
  }
  orderCreated(orderId, orderDetails) {
    this.events.push({ type: 'OrderCreated', orderId, orderDetails, timestamp: new Date() });
  }
  paymentReceived(orderId, paymentDetails) {
    this.events.push({ type: 'PaymentReceived', orderId, paymentDetails, timestamp: new Date() });
  }
  shipmentInitiated(orderId, shipmentDetails) {
    this.events.push({ type: 'ShipmentInitiated', orderId, shipmentDetails, timestamp: new Date() });
  }
  getEvents() {
    return this.events;
  }
}
Defines an OrderEvents class to manage order-related events such as creation, payment received, and shipment initiation using an event-sourcing approach.
// Instantiate the OrderEvents class
const orderEvents = new OrderEvents();

// Simulate creating an order
orderEvents.orderCreated('123', { item: 'Laptop', quantity: 1 });

// Simulate receiving a payment for the order
orderEvents.paymentReceived('123', { amount: 1000, method: 'Credit Card' });

// Simulate initiating shipment for the order
orderEvents.shipmentInitiated('123', { carrier: 'UPS', trackingNumber: '1Z999AA10123456784' });

// Retrieve and log all the events
console.log(orderEvents.getEvents());
Demonstrates how to use the OrderEvents class to record and retrieve an order's lifecycle events using an event-sourcing pattern.