Function Handler Code

Handler code is a short-running code-fragment which gets triggered as a response to a specific event. A collection of handlers constitute a Function.

A sample Function handler code is displayed below for reference.

eventing fun handler code

Functions offer an easy way to handle business logic changes. When your business logic undergoes modification, then you need to change only your Function handler code. With shorter development cycles, all the focus is around code-development without having to worry about infrastructure or configuration related changes.

Supported Event Handlers

The Eventing Service supports two event-handlers.

OnUpdate Handler

The OnUpdate handler gets called when a document is created or modified. The handler listens to data changes from the associated source bucket.

A sample OnUpdate handler is displayed below:

function OnUpdate(doc, meta)
 {
   log('document', doc);
   var time_rand = random_gen();
   dst_bucket[meta.id + time_rand] = doc;
 }

 {
   log(e);
  }

Following are a few limitations in the OnUpdate handler:

  • Distinguish between a document create and a document update operation is not possible.

  • If a document is modified several times in a short duration, due to deduplication, the handler calls, at times, get coalesced into a single event.

OnDelete Handler

The OnDelete handler gets called when a document is deleted. The handler listens to data changes from the associated source bucket. This handler also gets invoked during the expiry of a document.

A sample OnDelete handler is displayed below:

function OnDelete(meta)
{
    log('Document Deleted:', meta.id);
    if(meta.id < 10)
    {
       var this_user_id = meta.id;
       delete from `transactions` where user_id = TONUMBER($this_user_id);
       log('Deleted Orphaned Transactions for User:', this_user_id);
     }

 }

Following are a few limitations in the OnDelete Handler:

  • Distinguish between a delete as a result of expiration or from a user-triggered delete operation is not possible.

  • For deleted or expired documents, the value of the document cannot be retrieved.

Couchbase Server supports multiple OnUpdate and OnDelete handlers. You can have more than one handler in a Function definition.