10

Extensions for SAP Build Process Automation – Actions from CAP Node.js Service

 1 year ago
source link: https://blogs.sap.com/2023/01/13/extensions-for-sap-build-process-automation-actions-from-cap-node.js-service/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Extensions for SAP Build Process Automation – Actions from CAP Node.js Service

0 4 122

More information about the SAP Cloud Application Programming ModelWelcome to CAP

In this tutorial we will develop and deploy a CAP Node.js Service with simple functions and create an Action Project.The goal is to cover all the necessary steps to finally consume the CAP Service API functions in a Process, not to proivde a real use case.

Finally we will build and execute a process which combines simple no-code actions for a ToDo service and a CAP service API.

This is part of a blog series for Actions:
SAP Process Automation – Consume APIs with <no-code> using Actions.

Actions – High Level Architecture

We introduced the Action concept to simplify the experience for Citizen Developers to consume APIs without coding (no-code). Here an high level overview of the architecture.

ActionsOverview.png

Tutorial steps

Detailed information for CAP Business Service and Action Editor, the consumption should be known from other tutorials (Your first simple Action Project: End to End) and will be covered only high level.

EndToEnd-1.png

Prerequisites

  • Subscribe to SAP Business Application Studio in addtion to SAP Build Process Automation
    subscription-1.png
  • Create a Space if you don’t have one already
    spaces-1.png
  • Make sure your user has a Space Developer Role
    spaceDeveoper.png

SAP Business Application Studio

Develop Node.js Service

  • Click Create Dev Space
    CreateDevSpace.png
  • Define name demo and select kind Low-Code-Based…, click Create Dev Space
    CreateKind.png
  • The Dev Space is created and starting, when the status is running click demo to open
    openDevSpace.png
  • Application Studio will open and initialize, this will take some time
  • We will not create a project using the wizard, click cancel
    createProject.png
  • Close the Home tab, click x
  • Create a New Project from Template using the File menu
    FileMenu.png
  • From the templates, select CAP Project and click Start
    newCAP-1.png
  • Enter name sap-build-cap-sample-library and select feature MTA based…, click Finish
    runtime Node.js is already selected
    projectDetails.png
  • Guided Development and Home tab will be displayed, as we don’t use them, close both tabs
    GuidedHomeTab.png
  • From the Project Explorer we will change to the Explorer View, click View -> Explorer
    ViewExplorer.png
  • the Explorer will show all files of your project
    projectfiles.png
  • open the mty.yaml file with a text editor, to check the content, right-click on the file, select Open With…, select Editor click on Text Editor default
    mtafile.png
  • in the Explorer, click on folder srv and click New File icon
    newfile.png
  • use file name service.cds, press Enter and the empty file editor will open
  • create another file in the same folder, use file name service.js
  • select the file service.cds and copy the following code into the editor
    @Capabilities.BatchSupported : false
    
    service sap_build_cap_sample_library @(path : '/api/v1') {
      
      define type DataString {
        value : String;
      }
    
      define type DataInteger {
        value : Integer;
      }
      
      define type DataNumber {
        value : Double;
      }
    
      define type DataList {
          id : Integer;
          title: String;
          userId: Integer;
          completed: Boolean;
      }
    
      @Core.Description : 'toInteger'
      function toInteger(value : String) returns DataInteger;
    
      @Core.Description : 'toNumber'
      function toNumber(value : String) returns DataNumber;
    
      @Core.Description : 'toString'
      function toStr(value : Double) returns DataString;
    
      @Core.Description : 'addQuotes'
      function addQuotes(value : String) returns DataString;
    
      @Core.Description : 'listToString'
      action listToString(responseArray : array of DataList, field : String) returns DataString;
    
    }
  • select the file service.js and copy the following code into the editor
    module.exports = srv => {
    
        srv.on('toInteger', req => {
            const {value} = req.data;
    
            return { 'value' : parseInt(value) };
        });
    
        srv.on('toNumber', req => {
            const {value} = req.data;
    
            return { 'value' : parseFloat(value) };
        });
    
        srv.on('toStr', req => {
            const {value} = req.data;
    
            return { 'value' : value.toString() };
        });
    
        srv.on('addQuotes', req => {
            const {value} = req.data;
    
            return { 'value' : "'" + value + "'"};
        });
        
        srv.on('listToString', req => {
    
            var values = req.data.responseArray;
            var resultList = [];
            var field = req.data.field;
            if (values) {
                for (var i = 0; i < values.length; i++) {
                    resultList.push(values[i][field]);
                }
            }
    
            return { value : resultList.toString() };
        });
    }
  • Now you can use a Terminal to test the service already, click New Terminal
    newTerminal.png
  • Terminal window will open, enter command cds watch
    the service is locally build and can be tested
    cdswatch.png
  • to easily test the service, select the folder sap-build-cap-sample-library and click New File icon, use file name test.http
  • select the file test.http and copy the following code into the editor
    ###
    #
    # call toInteger
    #
    GET http://localhost:4004/api/v1/toInteger(value='20')
    
    ###
    #
    # call toNumber
    #
    GET http://localhost:4004/api/v1/toNumber(value='20.2')
    
    ###
    #
    # call toString
    #
    GET http://localhost:4004/api/v1/toStr(value=20.2)
    
    ###
    #
    # call addQoutes
    #
    GET http://localhost:4004/api/v1/addQuotes(value='abcd')
    
    ###
    #
    # call listToString
    #
    POST http://localhost:4004/api/v1/listToString
    Content-Type: application/json
    
    {
        "field" : "id",
        "responseArray": [
            {
                "id": 1,
                "title": "delectus aut autem",
                "userId": 1,
                "completed": false
            },
            {
                "id": 2,
                "title": "quis ut nam facilis et officia qui",
                "userId": 1,
                "completed": false
            }
        ]
    }     
  • To test a request, you can just click on Send Request in the file and you will see the response in a separate window
    testrequest.png

Deploy Service to BTP

We will use a script to build and deploy the service.

  • select the folder sap-build-cap-sample-library and click New File icon, use file name script.sh
  • select the file script.sh and copy the following code into the editor
    # set API endpoint and login to Cloud Foundry
    cf api https://api.cf.us10-001.hana.ondemand.com
    cf login
    # some needed npm settings
    npm update --package-lock-only
    npm set registry=https://registry.npmjs.org/
    # build the service locally
    mbt build -t gen --mtar mta.tar
    # deploy the service to the BTP space
    cf deploy gen/mta.tar
    # generate the openAPI spec for the service, used to create the Action project
    cds compile srv --service all -o docs --to openapi
  • execute the script in the terminal, enter command bash script.sh
    terminalScript.png
  • when asked, enter your Email and Password
  • during the execution of the script, the terminal will show informations for each step
  • login
    cflogin.png
  • build
    mbtbuild.png
  • deploy
    cfdeploy.png
  • generated openAPI spec
    openAPIspec.png
  • after the script execution, check in the BTP Cockpit, if the service is running
    serviceStarted.png

Generate OpenAPI spec

The openAPI spec was generated as part of the script in the previous step.This definition will be used to create the Action Project in SAP Build and needs some manual changes.

  • open the filesap_build_cap_sample_library.openapi3.json in the editor
    openAPIspecEditor.png
  • the following “paths” definitions must be updated with missing quotes (just replace the lines in the generated file)
        "/toInteger(value='{value}')": {
        "/toNumber(value='{value}')": {
        "/addQuotes(value='{value}')": {​
  • some “responses” / “schema ” definitions must also be updated,
    Note: this will not be necassary in future versions of the Action Editor.
  • just replace the lines in the generated file
    “/toInteger(value='{value}’)”: {
              "200": {
                "description": "Success",
                "content": {
                  "application/json": {
                    "schema": {
                          "$ref": "#/components/schemas/sap_build_cap_sample_library.DataInteger"
                    }
                  }
                }
              },
              "4XX": {
  • “/toNumber(value='{value}’)”: {
              "200": {
                "description": "Success",
                "content": {
                  "application/json": {
                    "schema": {
                          "$ref": "#/components/schemas/sap_build_cap_sample_library.DataNumber"
                    }
                  }
                }
              },
              "4XX": {
  • use the same definition for the following areas:
    “/toStr(value={value})”: {
    “/addQuotes(value='{value}’)”: {
    “/listToString”: {
              "200": {
                "description": "Success",
                "content": {
                  "application/json": {
                    "schema": {
                          "$ref": "#/components/schemas/sap_build_cap_sample_library.DataString"
                    }
                  }
                }
              },
              "4XX": {
  • after changing the definitions, select the file content (Ctrl-a) in the editor and copy (Ctrl-c)
  • create a new file in a local folder of your desktop (e.g. demo.json), open the file, paste the content and save the file (we will use the file later to create the Action Project)
    notepadOpenAPI.png

BTP Cockpit

Create Destination

In the SAP BTP Cockpit, create a destination that will be used in the Action Editor to test the Action and in the Process execution.

  • Get the Application Routes URL from the service, click on the Name
    serviceStarted.png
  • Copy the URL to use it later in the Destination definition
    applicationRoute-1.png
  • Create the Destination
    Name: Demo_CAP_Sample_Library
    URL:  <Application Routes url>/api/v1
    Additional properties: sap.applicationdevelopment.actions.enabled = true
    Additional properties: sap.processautomation.enabled = true
    CAPDestination-1.png

SAP Build Process Automation

Action Editor

From the Lobby of SAP Build, create an Action Project

  • Select Create, select Build an Automated Process
    createProcess.png
  • Select Actions
    createActions.png
  • Specify the name CAP Sample Actions and upload the API spec demo.json, click Create
    (Note: demo.json was created in section Generate OpenAPI spec)
    createCAPSampleActions-2.png
  • Select the actions from the list, click Add
    addActions-1.png
  • Your Action Project will contain the actions for the CAP service
    actionProject.png

Test Actions

You can test the execution of your action in the Action Editor. Lets test the Action listToString

  • Select listToString from the list, the action has input parameters field and values
  • Select Tab Test, we will use the Destination for the test and define the Input Values
    field: id
    values: id: 1, title: task1
    testListToString-3.png

In the Test you can specify only one value for a list. In the Response View you can see that the values are converted to a string (with more than one value they will be comma separated).
You can also try title as field and check the result.

Lets test the execution of some other actions.

  • toInteger
    testToInteger.png
  • toNumber
    testToNumber.png
  • addQuotes
    testAddQuotes.png

Release and Publish to the Library

To be able to use the Actions in a Process, we have to release and publish the Action Project.

  • Click Release
    release.png
  • Provide release information, click Release
    releaseInfo.png
  • Click Publish to Library
    releasePublish.png
  • On Publish Project, click Publish

Consumption in Process

If you just want to use simple Actions like toInteger, toString or addQuotes in your process you do not need the ToDo Action and you can ignore what is explained in Prerequisite.

Prerequisite:
for using the listToString Action in your process is the Action Project for ToDos, which is explained and created in the tutorial Walkthrough all steps using a simple REST API SAP Process Automation – Your first simple Action Project: End to End.
Note: Make sure to update the Action Project for ToDos with the latest OpenAPI spec available in the Walkthrough blog. There was a small but important change needed to get the sample process of this tutorial working.

Now lets look into the steps to use the listToString Action in your process.

Configure Destination for SAP Process Automation

To allow the usage of the BTP destination, you have to add the Destination in SAP Build Process Automation.

  • In the Settings or SAP Build Process Automation, select Destinations
  • Click New Destination
    select the Destination from the list and press Add
    addDestination.png
  • The destination is now added to the list and can be used
    destinations.png

Create Business Process and use an Action

  • From the Lobby select Create
  • Select Build an Automated Process, on next screen select Business Process
  • Enter Project Name CAP Sample and click Create
  • On the Create Process Dialog, enter the Process Name myCAPsample and select Create, the canvas will be shown
  • Select the + to add a step to your process
    addActionsToProcess.png
  • From the Browse Library add the actions get list of todos and listToString
    browseLib.png
  • create Destination variables todoService and capService
    todoService.png
    capService.png
  • Configure Process Details – Inputs, define Input field and click Apply
    (click on the canvas to display the Process Details)
    inputs.png
  • Define the Inputs for listToString, for input field select field from Process Start Inputs
    selectField.png
  • for Input tasks select list – responseArray from get list of todos
    Note: if list – responseArray cannot be selected, you may not have updated the ToDo Action Project with the latest openAPI spec and released/published to the library ?!
    inputTasks.png
  • definition of Inputs for listToString should look like
    processDef-1.png
  • Save, Release and Deploy
  • on the Deploy a project dialog select the Destinations for variables capService and todoService, click Confirm
    Confirm.png
  • Click on Deploy

Test the Process

  • On Monitor,select Manage –> Process and Workflow Definitions, click on myCAPSample
    monitorcap.png
  • click Start New Instance, on Start New Instance dialog specify the input paramer
    { "field" : "id" }​
    startInstance-1.png
  • click Start New Instance and Close
  • Select Monitor -> Process and Workflow Instances, clear all filters to make sure your instance is in the list
    runInstances.png
  • clck on line to display the details of the instance
    the result of the action listToString is shown as comma separated value string
    runInformation-1.png

Conclusion

Following this tutorial, you have seen all the steps to create a simple CAP Service and to consume the service in a process using Actions.


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK