Skip to Content
Technical Articles

SAP Cloud Application Programming Model – EP3

EP3: Event Handlers in SAP CAPM

Node.js APIs is both for design-time as well as runtime usage. All APIs can be accessed through the singleton CDS facade object.

const cds = require('@sap/cds')

These APIs are the center of all cds operations, for example, the cds command line interface is just a thin wrapper around these APIs.

Event handlers in SAP CAPM

  1. srv.on (event, entity?, handler)
  2. srv.before (event, entity?, handler)
  3. srv.after (event, entity?, handler)
  4. srv.reject (event, entity?)

srv.on (event, entity?, handler) 

Handlers registered with this method are run in sequence, with each handler being able to terminate the sequence.

srv.before (event, entity?, handler)

Registers a handler to run before the ones registered with .on(), that is, before the generic handlers. Commonly used to add custom input validations.

srv.after (event, entity?, handler)

Registers a handler to run after the generic handler. To be more precise: It runs on the results returned by the generic handler

srv.reject (event, entity?) 

Registers a generic handler that automatically rejects incoming request with a standard error message. You can specify multiple events and entities.

Let’s implement some of the events in our application

Providing Service Implementations

In Node.js, the easiest way to provide implementations for services is thru equally named .js files placed next to a service definition’s .cds file

./srv
  - cat-service.cds  # service definitions 
  - cat-service.js   # service implementation

 

Adding Custom Event Handlers

Service implementations essentially consist of one or more event handlers. Copy this into srv/cat-service.js to add custom event handlers.

Let’s implement the business logic now. write the below code.

module.exports = function (srv){
  srv.after ('READ','Employee', each => {
    if(each.status == 'A'){
        each.status = 'Act';
    }
  })
}

If server listening is stopped,Execute cds watch again from the Terminal to see the output in new tab. Otherwise, refresh the browser and check the output.

 

Episode 1: Click here for Episode 1

Episode 2: Click here for Episode 2

Git Setup: Click here for Git Setup

Connect Hana cloud with SAP Business Application Studio: Click Here for Connection Blog

 

I hope everyone enjoyed this blog, Please don’t forget to put comment and stay connected for more episodes.🙂

 

Regards

Nikhil Puri

 

 

 

 

 

Be the first to leave a comment
You must be Logged on to comment or reply to a post.