Event Handler
In SAP Cloud Application Programming Model, everything that happens at runtime is an event that is sent to a service. They are a powerful means to extend CAP. An event handler is simply a method, that is executed when something happens in the application.
If you need a specific service to react to a specific event, you register an event handler using srv.<phase>(<event>)
, where
srv
is the instance of the service that you are extending,<phase>
is one of on
, before
, or after
(see section Event Phases) and<event>
is any kind of named event as a string (e.g. 'READ'
).
Once a service has an event handler for a specific event, it becomes a consumer for that event. Using srv.emit(<event>)
, a service can send arbitrary events. These events then get consumed by other services that have event handlers registered for the respective event.
Watch this video to learn about the custom event handler phases.
In the first example, code is added before Orders are created through a post or put request or so. For example, one might verify that there's enough stock or execute any check before the actual request is processed.
In a second example, the code is executed after books are read.
And in the third example, code is registered to run instead of the generic framework handler.
In the case of an external service, there wouldn't be anything the framework could do,so you must provide an on handler, but you can also use the on hook to override generic CRUD handlers. However, it is recommended to use a generic implementation and only diverge from it if you need different logic.
Also know that you can add more than one event handler for the same event, for example two before handlers for the same order creation event.
Likewise, a single handler can handle multiple events. For example, just omit the book string in the second example,to have a handle that is called after all entities are read, no matter they are Books, Authors, or Orders.
Request objects are passed in the event handlers , they provides all sorts of information about the context, like the request data or the method,like get post and so on.
Request objects are also used to provide error messages back to the client, or to register another set of handlers for the request lifecycle, like when the request has completed, succeeded, or failed.
capire - Core Services APIs (cloud.sap)