This is the continuation of my previous blog, where I started with a very simple project of creating REST services using CAP leveraging CDS and integrating with BTP services.
In this blog, I will enhance the CAP project with below tasks –
- Use case modeling – Time for some Design Thinking.
- Create relationships between entities.
- Visualize entity and relationships in CDS graphical modeler.
- Create custom event handler and add a simple logic.
It is always easy to understand with a working example. So I will be using this use case and enhancing it further in subsequent blogs.
Let us get started!
Task – 1 : Use case modeling
Time for some design thinking. Here, I have tried to explain the entities with the help of UML so that we can relate to it before development.
Figure-1
As you see in the above diagram –
- Users are associated with Roles – either Admin, Manager, Employee.
- User (Admin) – Can create users (managers, employees).
- User can assign tasks to his/her team.
- Tasks are categorized using categories.
Here, Users, Roles, Tasks and Categories will translate to the entities. Let us check it out in our next step.
Task – 2 : Defining entity relationships in CDS
Note: There is no one specific way to model your entities. So, feel free to model your entities and relationships. Take this as a reference and surely comment on this blog to help me understand your perspective.
- Below is the snippet of data-model.cds from my CAP project.
namespace sap.capire.taskmanager; using { cuid, managed } from '@sap/cds/common'; entity Categories : managed { key name : String; active : Boolean default TRUE; } entity Roles : managed { key name : String(50); active : Boolean default TRUE; } entity Users : managed { key email : String; firstName : String not null; lastName : String not null; phone : String not null; password : String; active : Boolean default TRUE; userRole : Association to one Roles @assert.target; tasks : Composition of many Tasks on tasks.owner = $self; parent : Association to one Users; } entity Tasks : cuid, managed { name : String not null; description : String(4000); status : Boolean default FALSE; reminderCount : Integer; owner : Association to one Users; category : Association to one Categories @assert.target; }
- Let us take a quick look at the entities
- A user has an association with a Role. (Association)
- A task is associated with a Category. (Association)
- A user can have one or more tasks associated with it. (Composition)
- A user can have a parent associated with it.(Association)
Task – 3 : Visualize entities in CDS graphical modeler
- Business Application Studio provides a nice extension to visualize the entities in a graphical view.
- In the “Explorer” pane on left hand side – check for “CAP DATA MODELS AND SERVICES“Figure-2
- Once you click “Open with CDS Graphical Modeler“, you will see the below entity relationship diagramFigure-3
- To understand more about the capabilities of CDS graphical modeler, check this link
Task – 4 : Custom event handler for entity – USER
Till now we have defined very simple service to read and write data in the database. But in most business cases, we have to add custom logic, integrate with external system. Let us add a simple event handler for USER entity. Let us check this out –
- I am going to create a event handler which will generate password and save it on user entity when a new user is created.
- For this, I have created a event handler service – UserService.java inside handler folder inside src/src/main/java/com/sap/cap/taskmanager
package com.sap.cap.taskmanager.handlers; import java.security.SecureRandom; import com.sap.cap.taskmanager.util.TaskManagerUtil; import com.sap.cds.services.cds.CqnService; import com.sap.cds.services.handler.EventHandler; import com.sap.cds.services.handler.annotations.Before; import com.sap.cds.services.handler.annotations.ServiceName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import cds.gen.adminservice.User; import cds.gen.adminservice.User_; @Component @ServiceName("AdminService") public class UserService implements EventHandler{ Logger logger = LoggerFactory.getLogger(UserService.class); private static final String PASSWORD_PREFIX = "Welcome"; @Before(event = CqnService.EVENT_CREATE , entity = User_.CDS_NAME) public void onCreate(User userData) { String password = PASSWORD_PREFIX + String.valueOf(TaskManagerUtil.generateRandomNumber()) ; userData.setPassword(password); logger.info("Updated default password for {}", userData.getFirstName()); } }
- TaskManagerUtil.generateRandomNumber() just generates 5 digit random number which will be used to create a default password.
- Let us understand some keywords in the handler class.
- Your event handler class has to implement marker interface EventHandler which help CAP JAVA runtime to identify custom event handler classes.
- Here I have used @Before annotation, which is invoked before saving the entity to database.
- @ServiceName points to the default service where you have defined your entity.
- CAP JAVA SDK generates data accessor interfaces for entities defined in the CDS model. In this example, I have directly accessed user data in the method onCreate().
- I highly recommend quickly browsing through the below two links
Let us test this quickly on local –
- Start your application.
- Add the below request in requests.http file
POST http://localhost:8080/odata/v4/AdminService/User Content-Type: application/json Authorization: Basic authenticated: { "firstName": "John", "lastName": "Doe", "email": "john.doe@remindme.com", "phone": "9878768765", "userRole_name": "Admin" }
- Check logs – “Updated default password for John”
- Also, check in database explorer, you should see the default password updated as shown belowFigure-4
Conclusion
I hope, this has helped you to take one step ahead in your cloud journey with CAP and SAP BTP. As always – Stay curious! Keep learning!
Stay tuned to my next blog, where I am planning to integrate this CAP project with SAP Event Mesh to explore event driven architecture.
To get more updates about this topic follow below pages –
Feel free to “like“, “Share“, “Add a Comment” and to get more updates about my next blogs follow me – Avinash Vaidya