Logic Event Rule Types

Event rules (and their close cousins early events and commit events) are server-side JavaScript-code business logic that get executed whenever a row is inserted, updated, or deleted (when you have enabled the rule for that type of event). Event rules are not required to return a value. If they do, that value is ignored. Like formula rules and validation rules, event rules can access the values of the current row, the old row, and any parent rows.
lac40
Event rules (and their close cousins early events and commit events) are server-side JavaScript-code business logic that get executed whenever a row is inserted, updated, or deleted (when you have enabled the rule for that type of event). Event rules are not required to return a value. If they do, that value is ignored. Like formula rules and validation rules, event rules can access the values of the current row, the old row, and any parent rows.
Event rules provide access to external/reusable JavaScript functions by way of the Nashorn JavaScript engine. Event rules are a key architectural element, providing:
  • Re-use.
    CA Live API Creator
     reuses table events over all resources built on that table. When
    CA Live API Creator
    receives resource updates, it dealiases them onto the underlying base table objects.
  • Encapsulation.
    CA Live API Creator
    invokes event logic as updated requests are processed.
You can create event rules that:
  • Insert (audit) changes for the current entity.
  • Call an external resource.
  • Send email.
  • Update a calendar system.
  • Post a message on a queue.
  • Call a push notification engine.
You can combine event rules with external resources and systems. For example, your event rule can determine the lat/long coordinates to be used in a Google map for product delivery. You combine them by using an event rule that passes a customer's address to a resource which in turn calls Google Geocode.
Event rules can begin with the incoming request, the final response, and early- and post-commit processing on a transaction.
In this article:
2
Specify Event Rule Firing
You can specify when the event is fired. Event rules interact with other logic and fire at predetermined times during logic execution, depending on the event rule type:
  • Early Event.
     Fires before your logic executes. The row data is not subjected to formulas and other derivations. You can change the row and the changes are subjected to validations, other chained logic, and saved.
  • Event.
     Fires after row-logic is completed. The row data reflects derivation results. You can change the row but you must ensure that required logic is executed using the 
    logicContext.save()
    method.
  • Commit Event.
    Fires after row-logic is completed for all the rows in the transaction. The rows reflect logic processing. You cannot change the rows.
For more information about logic execution, see Logic Execution.
Rules vs. Events
Rules reduce the amount of code you must write. Using rules requires that you transition to "think spreadsheet". Use rules before you build your events. Events are a complement to the other declarative forms of rules. Events address issues that rules do not address and they have unlimited flexibility.
"Think Spreadsheet" Rules Example
The following example is a common example. Assume that you need a sum (or count) of child rows for a parent. For example, a sum of unpaid order amounts. Events are a familiar concept. Experienced programmers might envision the following code, perhaps as part of the Add Order use case, to adjust sums and counts:
Define Order event MaintainCount as
if (logicContext.initialVerb == 'INSERT' && row.isPaid == false) { // row is the order
    customer = row.customer; // parent accessor
    customer.balance += row.amountTotal;
    logicContext.update(customer);
}
Consider the following other use cases:
  • Delete Order: Decrement the count, only if the order
    isPaid
    .
  • Change
    Order.isPaid:
     Watch for such a change, and if you detect it, adjust the sum by
    amountTotal
    .
  • Change
    Order.amountTotal
    : Watch for such a change, and if you detect it, adjust the sum by the difference.
  • Reassign Order: Often overlooked, reduce the old customers'
    balance
    , increase the new one, only if the order
    isPaid
    .
If the qualification condition or summed field (
amountTotal
) is itself derived, perhaps from still another table, the code can get complicated. Define a sum or count and all of the boilerplate code to address these use cases are handled without error. Sums and counts operate like spreadsheets:
 
Spreadsheet
Reactive Logic
User
Defines cell formula:
Cell A =   Sum(ColumnB)
 Defines database column:
Customer.balance =   sum(orders.amountTotal where paid = false)
API Creator
Watches for changes:
  • ColumnB
    changes
  • ColumnB
    new rows
  • ColumnB
    deleted rows
Watches for changes:
  • amountTotal
    changes
  • paid
    changes
  • Foreign Key changes (
    Orders.CustomerName
    )
  • Inserted
    Orders
  • Deleted
    Orders
 
Reacts to changes:
  • Adjust
    CellA
Reacts to changes:
  • Adjust
    Customer.balance
    (SQL and transaction management)
Create Event Rules
  1. In API Creator, in the Manage section, click 
    Rules
    .
    If your API does not have existing rules, the Welcome to Rules page appears. If your API has existing rules, they are listed on the By entity tab by default.
  2. Complete one of the following:
    • If you have not defined any rules, on the Welcome to Rules page, click 
      Create a Rule
      .
    • If you have at least one rule defined, on the By entity tab, click 
      Create New Rule
      .
  3. Do the following:
    1. Select one of the following event rule types:
      • Event
      • Early Event
      • Commit Event
    2. Select the entity to which the rule applies.
    3. Click 
      Create Rule
      .
  4. The event rule page appears. The following image shows the
    Allocate payments to outstanding orders
    event rule for the Sample API:
    event rule type.png
  5. Define the parameters of the rule, and then click
    Activate and Close
    :
    Event name
    The name of the event rule.
    Leave this field blank for the system default.
    Entity
    The name of the entity being acted upon.
    Code
    The code for your entity rule. You can access and insert JavaScript code examples into the code editor.
    For more information about the code examples that are available for event rules, see Code Examples.
    Example:
     A typical example is an auditing event. The use of the current/old bean in making your logic conditional:
    if (row.amount_total != oldRow.amount_total) 
      SysLogic.insertChildFrom("purchaseorder_audit", logicContext);
    Active
    Select to activate the rule.
    Default:
     Cleared
    The API must be complete.
    Asynchronous
    Select this checkbox to have 
    CA Live API Creator
     execute the event rule asynchronously, independent of the current transaction. The execution of the event does not affect the current transaction. Running your request event asynchronously can be helpful for processes that might take a long time, such as making an external call or sending an email.
The event rule is created. The list of rules display.
Use Event Rules
You specify your logic in server-side JavaScript. Your logic is passed key information required for its operation.The logic engine invokes the following variables on every update, providing key contextual information:
  • row
    . The 
    row
     object reflects client changes from JSON, and all logic processing. It has attributes for every column, so you can refer to an order's 
    row.amount_total
    . It also provides role accessors, so you can refer to an order's 
    row.customer.balance
    , or can obtain a collection of 
    row.lineitems
     (a collection of lineitem rows). Rows also provide persistence to read/alter data.
    For more information about the row object, see Row Objects.
  • oldRow
    . The 
    oldRow
     object reflects the row before the transaction started. This object is from the database read. It has the prior values of the object being updated, so you can detect changes.
  • logicContext
    .
    The 
    logicContext
     object provides many services, such as verb (insert, update, or delete), services to read and write data (including logic enforcement), create objects, and event logging.
    For more information about the 
    logicContext
     object, see The logicContext Object.
  • SysLogic.
     System methods, including the 
    InsertIntoFrom()
    allocateFromTo()
    , and 
    findWhere()
     system methods.
    For more information:
Event rules have access to the standard variables including 
row
oldRow
, and
logicContext
.
For more information:
Event Context
CA Live API Creator
 passes contextual variables to your event rules, such as
row
,
oldRow
, and
logicContext
. Event rules can use the 
SysLogic
object, which provides logic services such as the
allocateFromTo()
system method, the
findWhere()
system method, and the
insertChildFrom()
system method. Event rules can also invoke JavaScript methods, including systems-supplied ones.
 Database validation depends on your validation logic. 
CA Live API Creator
must ensure that it executes your validation logic after you make changes. Database validations apply to events. 
CA Live API Creator
can execute update logic multiple times, but fires associated events only once per transaction.