Logic Event Rule Types

Event rules (and their close cousins early event rules and commit event rules) 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.
lac32
Event rules (and their close cousins early event rules and commit event rules) 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 functions by way of Nashorn, an open-source implementation of JavaScript. Event rules are a key architectural element, providing:
  • Re-use.
    Event rules are re-used over all resources built on that table. When
    CA Live API Creator
    receives resource updates, they are de-aliased onto the underlying base table objects.
  • Encapsulation.
    CA Live API Creator
    invokes event logic as updated requests are processed.
You can create event rules to:
  • 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 user-defined endpoints, or resources, to external systems. For example, you can return 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:
  • 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.
  • 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.
  • 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 event rules. Event rules are a complement to the other declarative forms of rules. Event rules 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. Event rules 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:
  1. Delete Order: Decrement the count, only if the order
    isPaid
    .
  2. Change
    Order.isPaid:
     Watch for such a change, and if you detect it, adjust the sum by
    amountTotal
    .
  3. Change
    Order.amountTotal
    : Watch for such a change, and if you detect it, adjust the sum by the difference.
  4. 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 another table, the code can get complicated. If you define a sum rule or count rule, 
CA Live API Creator
 addresses these use cases by handling the boilerplate code without error. Sum rules and count rules 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, with your API open, in the Manage section, click
    Rules
    .
    A list of rules display on the By entity tab.
  2. Click 
    Create New Rule
    .
    The rule creation page appears.
  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
      .
      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
  4. Define the parameters of the rule:
    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.
  5. Click 
    Activate and Close
     to return to the list of rules.
The event rule is created.
Use Events
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.
  • logic.sys
    .
     System methods, including the 
    InsertIntoFrom
    allocateFromTo
    , and 
    findWhere
     system methods.
    For more information about the system methods (rule/logic types), see Rule Types.
Event rules have access to the standard variables including 
row
oldRow
, and
logicContext
.
For more information:
  • About standard variables and how the logic engine provides contextual information, see Quick Reference.
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 event rules. 
CA Live API Creator
can execute update logic multiple times, but fires associated event rules only once per transaction.
 For more information:
  • About the
    logicContext
    object, including how to update an object using the 
    touch
     method, see The logicContext Object.
  • About system methods, see Rule Types.
  • About a list of the methods, including JavaScript context variables, see Quick Reference.