Orchestrated Saga for Booking Vacation Packages
Illustrate the orchestration approach by implementing a saga in JavaScript for booking vacation packages, coordinating between flight booking, hotel reservation, and car rental services.
class VacationPackageSaga {
constructor(flightService, hotelService, carRentalService) {
this.flightService = flightService;
this.hotelService = hotelService;
this.carRentalService = carRentalService;
}
async bookVacationPackage(vacationDetails) {
try {
const flightBooking = await this.flightService.bookFlight(vacationDetails.flight);
const hotelBooking = await this.hotelService.bookHotel(vacationDetails.hotel);
const carRental = await this.carRentalService.rentCar(vacationDetails.carRental);
console.log('Vacation package booked successfully');
} catch (error) {
console.error('Booking failed:', error);
// Here we would add rollback logic for each service
}
}
}
Defines a VacationPackageSaga class that orchestrates booking a vacation package by coordinating between flight booking, hotel reservation, and car rental services. The bookVacationPackage method attempts to book each part of the vacation, and it includes a placeholder for rollback logic in case any part fails.
// Instantiate the saga with service instances
const vacationSaga = new VacationPackageSaga(flightService, hotelService, carRentalService);
// Vacation details object
const vacationDetails = {
flight: { from: 'City A', to: 'City B', date: '2023-07-10' },
hotel: { name: 'Hotel XYZ', checkIn: '2023-07-10', checkOut: '2023-07-15' },
carRental: { type: 'SUV', pickUpDate: '2023-07-10', dropOffDate: '2023-07-15' }
};
// Executing the vacation package booking
vacationSaga.bookVacationPackage(vacationDetails);
Demonstrates how to instantiate the VacationPackageSaga with service instances and execute a vacation package booking by providing vacation details. This showcases using the saga to orchestrate the booking process.