Event Rule Types

Event rules (and their close cousins early event rules, commit event rules, and preinsert 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 do not have to return a value. If they do,  ignores that value. Event rules can access the values of the current row (row), the previous row (oldRow), and any parent rows. Event rules can begin with the incoming request, the final response, and early- and post-commit processing on a transaction.
calac41
Event rules (and their close cousins early event rules, commit event rules, and preinsert 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 do not have to return a value. If they do,
CA Live API Creator
 ignores that value. Event rules can access the values of the current row (
row
), the previous row (
oldRow
), and any parent rows. Event rules can begin with the incoming request, the final response, and early- and post-commit processing on a transaction.
Event rules provide access to external/reusable JavaScript functions by way of the Nashorn JavaScript engine. 
CA Live API Creator
 reuses event rules over all resources built on that table. As 
CA Live API Creator
receives resource updates, it de-aliases them onto the underlying base table objects. 
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.
    For example, you can have your event rule determine the lat/long coordinates to be used in a Google map for product delivery. You do this using an event rule that passes a customer's address to a resource which in turn calls Google Geocode.
  • Send email.
  • Update a calendar system.
  • Post a message on a queue.
  • Call a push notification engine.
In this article:
2
Specify When the Event is Fired
Event rules interact with other logic and fire at predetermined times during logic execution. The time when the event fire depends on the event rule type:
  • Event.
     Fires after row-logic is completed. The row data reflects derivation results.
    You can change the row within the code of an event rule, 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.
  • Pre-Insert event.
     Fires before sending the row to the database on insert. You can use pre-insert event to generate the primary key or compute a non-nullable attribute before inserting a row to the table. 
 If you want to change primary keys within an event, define the change only within the code of an early, commit, or pre-insert event rule.
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.
The following "think spreadsheet" rules example is a common example of using an event rule. 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 to adjust sums and counts, perhaps as part of the Add Order use case:
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 previous 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
 handles the boilerplate code to address these use cases 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)
CA Live API Creator
Watches for changes:
  • ColumnB
    changes
  • ColumnB
    new rows
  • ColumnB
    deleted rows
Watches for changes:
  • amountTotal
    changes
  • paid
    changes
  • Foreign key changes (for example,
    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 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. Click 
    Create a Rule
    .
  3. Do the following:
    1. Specify when the event is fired by selecting one of the following event rule types:
      • Event
      • Early Event
      • Commit Event
      • Preinsert Event
      If you want to change primary keys within an event, select
      Early Event
      ,
      Commit Event
      , or
      Preinsert Event
      .
    2. Select the entity to which the rule applies.
    3. Click 
      Create Rule
      .
  4. Define the parameters of the rule, and then click
    Activate and Close
    :
    Title
    The title for the event rule. The title for rules does not affect logic processing. To apply a default value, leave this field blank.
    Required:
     No
    Entity
    The name of the entity being acted upon.
    Topics
    The topic that you want to associate to this rule.
    For more information about topics, see Manage Topics.
    Code
    The code for your event 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.
    You can have 
    CA Live API Creator
     return an object and assign it to a row attribute. This object represents the current date, time, or timestamp on the database server at the instant the resulting SQL is executed on the database server. You can do this by way of the 
    SysUtility
     JavaScript object's 
    databaseNowDeferred()
     method or the 
    sqlSnippetDeferred()
     method.
    For more information about these methods, see The SysUtility Object.
    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.
    Name
    The name of the event rule. Leave this field blank for the system default.
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
    and
    oldRow
    . The 
    row
     object reflects client changes from JSON, and all logic processing. 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.
    For more information about row logic, see Logic Execution.
  • Logic context.
    You can use the 
    logicContext
     object methods to read/write other rows.
    For more information about this object, see The logicContext Object.
  • Logic services.
    You can use the 
    SysLogic
    object methods in validation rules, formula rules, and event rules.
    For more information about this object, see The SysLogic Object.
Event Context
CA Live API Creator
 passes contextual variables to your event rules. You can use the system methods that are included with the 
SysLogic
 object in event rules. You can also define the code for your event rule to invoke other 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
SysLogic
object, see The SysLogic Object.