Implementing Choreographed Saga for E-commerce Transactions
Demonstrate the implementation of a choreographed saga in JavaScript for handling an e-commerce transaction, including order creation, payment processing, and stock update.
const EventEmitter = require('events');
const eventEmitter = new EventEmitter();
// Mock services
class OrderService {
static createOrder(data) {
console.log('Creating order', data);
// Emulate order creation
eventEmitter.emit('orderCreated', { orderId: 123, ...data });
}
}
class PaymentService {
static processPayment(order) {
console.log('Processing payment for', order);
// Payment logic
eventEmitter.emit('paymentProcessed', order);
}
}
class StockService {
static updateStock(order) {
console.log('Updating stock for', order);
// Stock update logic
eventEmitter.emit('stockUpdated', order);
}
}
Sets up basic services and their methods to simulate order creation, payment processing, and stock update. Each service method emits an event upon completion.
// Event listeners
eventEmitter.on('orderCreated', (order) => {
// Proceed to process payment upon order creation
PaymentService.processPayment(order);
});
eventEmitter.on('paymentProcessed', (order) => {
// Proceed to update stock once payment is processed
StockService.updateStock(order);
});
eventEmitter.on('stockUpdated', (order) => {
console.log(`Transaction completed for order: ${order.orderId}`);
});
Defines event listeners for 'orderCreated', 'paymentProcessed', and 'stockUpdated' events to move the transaction through the required stages.
// Initiating a saga example
OrderService.createOrder({ item: 'Smartphone', quantity: 1, price: 599 });
Initiates the saga by creating an order. The rest of the process is handled through event-driven callbacks.