Blog

How to use Cloud Code Event Handlers (Overview)

by on May 3, 2015

There are two types of custom (server-side) business logic supported by Backendless – timers and event handlers. In my previous posts have reviewed the entire process of developing, testing and deploying timers. Now I’m going to focus on event handlers.

An event handler is a piece of custom server-side logic (Cloud Code) which can be plugged into the API processing chain. The diagram below illustrates how API processing works – the gray box is the server-side of Backendless. As you can see, there are two blocks where custom business logic can be placed – the “before” and “after” handlers:

The approach is very powerful as it allows to either completely override the default implementation of the API logic or augment its behavior. The “before” handlers can “short-circuit” the invocation chain by interrupting it and returning an error to the calling app thus preventing the invocation from the normal completion. Additionally, the handler can modify the incoming API call arguments if needed. Likewise, the “after” handler can modify the return value. All of this is in addition to any kind of custom logic that can reside in the handler implementation.

Backendless server-side handlers must be implemented in Java, however we are working on adding support for other languages. There is a mini-framework for implementing handlers. For example, consider the code below which is a “before” handler for the user registration API in the User Service:

package com.backendless.orderprocessing.events.user_service;
import com.backendless.servercode.RunnerContext;
import com.backendless.servercode.extension.UserExtender;
import java.util.HashMap;
public class RegistrationEventHandler extends UserExtender
{
  @Override
  public void beforeRegister( RunnerContext context, HashMap regProps ) throws Exception
  {
    // your custom business logic code goes here
  }
}

When deployed, the code will be executed every time a user is registering with your app. Notice the class extends the UserExtender class. That base class must be used for any event handler which works with the User Service APIs. The second argument (regProps) in the beforeRegister method is a collection of the user registration properties. The handler may perform user properties validation or any other server-side logic.

In other posts, I review the process of developing event handlers for various Backendless services, using code generator, debugging and deploying custom code.

Enjoy!