Adding Custom Business Logic

Objectives
After completing this lesson, you will be able to:

After completing this lesson, you will be able to:

  • Add custom business logic

Add Custom Business Logic to Your Application

Usage Scenario

In this exercise, you will add custom code to the CAP service to implement conditional formatting of certain cells of your work list. Depending on the value of the properties impact and criticality respectively, cells in the table of our work list page will change color.

Exercise Options

You can perform this exercise in two ways:

  1. Live Environment – using the instructions provided below, you can perform the tasks in the SAP BTP Free Tier account
  2. Platform Simulation – follow the step-by-step instructions within the simulation
Note
We are strongly recommending first performing the tasks in the live environment.

Live Environment

In this exercise, you will create a JavaScript file to implement dynamic color coding.

Prerequisites

Before proceeding with this exercise please first ensure that you:

  • generated a UI channel.
  • are familiar with JavaScript coding.

Steps

  1. Add Custom Code.

    1. In the project, go to folder srv, representing the service, and select New File in the context menu.

    2. Enter risk-service.js as a name.

    3. Select the new file in the explorer, an editor opens.

    4. Enter the following lines into the editor:

      Note
      The defined constant for the BusinessPartners will be used in a later step.
      Code snippet
      // Imports
       const cds = require("@sap/cds");
      
       /**
          * The service implementation with all service handlers
          */
       module.exports = cds.service.impl(async function () {
          // Define constants for the Risk and BusinessPartners entities from the risk-service.cds file
          const { Risks, BusinessPartners } = this.entities;
      
          /**
          * Set criticality after a READ operation on /risks
          */
           this.after("READ", Risks, (data) => {
              const risks = Array.isArray(data) ? data : [data];
      
              risks.forEach((risk) => {
                if (risk.impact >= 100000) {
                  risk.criticality = 1;
                } else { 
                  risk.criticality = 2;
                }
             });
          });
       });
      Copy code
    5. Save the file.

    6. In the browser, reload the page of the SAP Fiori Elements app.

      It now shows our work list with the columns Priority and Impact with color and an icon, depending on the amount in impact.

      Note
      Keep your application running in your web browser, you will need it later.

  2. Undergo an investigation of the custom code.

    Because your file is called risk-service.js and shares the same name as your service definition file risk-service.cds, CAP automatically treats it as a handler file for the service defined in there. CAP exposes several events1 and you can easily write handlers like the one above. If you want to use a different name for the JavaScript file, you have to use @(impl:...) notation2.

    The event after is triggered after a READ is carried out for our Risks entity. In your custom handler, you get all the data, in this case all the risks that were read according to the query. You can loop over each of them and, if needed, adjust the data of the response. In this case, the code changes criticality value when the impact is larger than 100000. The new values for criticality are then part of the response to the read request.

    How is this change reflected in the UI? To achieve this, you have to go back to the annotations you created in the exercise: Generate a User Interface Using SAP Fiori Elements, where you find your app/risks/annotations.cds file. There you had the two columns prio and impact annotated with an additional Criticality annotation.

    This annotation points to the criticality property of your service.

    Note
    Criticality with an upper-case C is the annotation, while the property name criticality could also be called different opposed to the annotation.

    As you now set different values in your custom handler for criticality, the SAP Fiori elements application translates these into icons and colors, which you can see in the UI.

    Code snippet
    annotate RiskService.Risks with @(UI : {
        ...
        ...
        LineItem : [
           ...
           ...
           {
              Value : prio,
              Criticality : criticality
           },
           {
              Value : impact,
              Criticality : criticality
           },
        ],
     });
    Copy code

    You can find out more about the possible values of the Criticality annotation here3. This, however, is just one of the many sections of the OData Annotation vocabularies for UI4 and Common5 usage.

    Platform Simulation

    Click on the Start button below to open a simulation of the platform. Then follow the step-by-step instructions to add custom business logic to your application.

Result

Good work! You performed the necessary steps for adding a custom business logic to your application. You are now able to add in a flexible fashion custom logic to future applications.

Reference Links: Adding Custom Business Logic

For your convenience, this section contains the external references in this lesson.

If links are used multiple times within the text, only the first location is mentioned in the reference table.

Ref#SectionContext text fragmentBrief descriptionLink
1Explanation of the Custom CodeCAP exposes several eventsHandler registration APIhttps://cap.cloud.sap/docs/node.js/services#event-handlers
2Explanation of the Custom Codeyou have to use @(impl:...) notation.Providing Custom Implementationshttps://cap.cloud.sap/docs/guides/providing-services#service-impls
3Explanation of the Custom Codepossible values of the Criticality annotationCriticality typeshttps://github.com/SAP/odata-vocabularies/blob/main/vocabularies/UI.md#CriticalityType
4Explanation of the Custom CodeOData Annotation vocabularies for UI and CommonUI vocabularyhttps://github.com/SAP/odata-vocabularies/blob/main/vocabularies/UI.md
5Explanation of the Custom CodeOData Annotation vocabularies for UI and CommonCommon vocabularyhttps://github.com/SAP/odata-vocabularies/blob/main/vocabularies/Common.md
Note
For GitHub, a registration is required.

Log in to track your progress & complete quizzes