Exercise 5: Cross-Service Communication
5.1 Understanding Cross-Service Scenarios
Cross-service communication simulates real microservices architectures where:
- BookshopService handles core business operations (book promotion, inventory)
- ReviewsService manages review workflows (approval, moderation, statistics)
- Services need to synchronize data and trigger actions across domains
5.2 Implement Cross-Service Communication
1. Enhanced Books.js with cross-service functionality:
Update
webapp/localService/mainService/data/Books.js
to demonstrate how book operations can trigger review-related actions:
module.exports = {
getInitialDataSet: function (contextId) {
// ... existing code from previous exercise ...
},
executeAction: function (actionDefinition, actionData, keys) {
console.log('Executing action:', actionDefinition.name);
switch (actionDefinition.name) {
case 'setDiscount':
// ... existing setDiscount code ...
break;
case 'promoteBook':
console.log('📚 Starting book promotion with cross-service integration...');
// Step 1: Update book in main service
const bookEntries = await this.base.fetchEntries(keys);
const bookData = bookEntries[0];
if (!bookData) {
this.throwError('Book not found', 404);
return;
}
// Update the book with promotion status
await this.base.updateEntry(keys, {
description: 'PROMOTED: ' + bookData.description,
stock: bookData.stock + 10, // Add promotional inventory
});
console.log('✅ Book updated in BookshopService');
// Step 2: Cross-service communication to ReviewsService
// Add a promotional review via the reviews service
this.base
.getEntityInterface('Reviews', 'reviews')
.then(function (reviewService) {
if (reviewService) {
console.log('🔄 Connecting to ReviewsService...');
return reviewService.addEntry({
ID: `promo-${Date.now()}-${Math.random().toString(36).substring(7)}`,
book_ID: keys.ID, // Link to the promoted book
reviewer: 'Marketing Team',
rating: 5, // Promotional reviews are always 5-star
comment: `📈 PROMOTIONAL: "${bookData.title}" has been featured! Don't miss this amazing read.`,
createdAt: new Date().toISOString(),
createdBy: 'system',
modifiedAt: new Date().toISOString(),
modifiedBy: 'system',
IsActiveEntity: true,
HasActiveEntity: false,
HasDraftEntity: false,
});
}
})
.then(function () {
console.log('✅ Cross-service promotional review added to ReviewsService');
})
.catch(function (error) {
console.error('❌ Failed to add cross-service review:', error);
// Don't fail the whole operation if review creation fails
});
return {
message: 'Book promoted successfully with cross-service review integration!',
promoted: true,
crossServiceIntegration: 'Reviews service notified',
};
default:
this.throwError(`Action ${actionDefinition.name} not implemented`, 501);
}
},
};
2. Start the application:
# from folder ex5
npm run start-mock
# or from root folder
npm run start:ex5
If you now start the app, in the List Report the data from the
getInitialDataSet
method of the
Books.js
file is shown.
If you select a book in the List Report and press the Button
CAP Promote Book
, the book is promoted and a promotional review is created in the
ReviewsService
.
As we did not integrate the Service in the List Report, we can check the created review by opening the URL http://localhost:8085/reviews/Reviews in the browser.
There should be now at least one entry with the comment:
"comment": "📈 PROMOTIONAL: \"Biography Book 1\" has been featured! Don't miss this amazing read."
5.3 Key Benefits of Cross-Service Communication
- Realistic Integration Patterns: Book promotions triggering review creation mirrors real microservices workflows
- Audit Trails: System activities are logged across service boundaries for compliance
- Service Validation: Cross-service data integrity checks ensure consistent state
- Error Resilience: Graceful handling of cross-service failures maintains system stability
Next Steps
Exercise 6
will show how to implement context-based isolation (multi-tenancy) where different tenants can have separate
datasets and business logic variations using the
?sap-client=
query parameter.