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. WhenCA Live API Creatorreceives resource updates, they are de-aliased onto the underlying base table objects.
- Encapsulation.CA Live API Creatorinvokes 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 thelogicContext.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 asif (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 orderisPaid.
- ChangeOrder.isPaid:Watch for such a change, and if you detect it, adjust the sum byamountTotal.
- ChangeOrder.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 orderisPaid.
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:
| Defines database column:
|
API Creator | Watches for changes:
| Watches for changes:
|
Reacts to changes:
| Reacts to changes:
|
Create Event Rules
- In API Creator, with your API open, in the Manage section, clickRules.A list of rules display on the By entity tab.
- ClickCreate New Rule.The rule creation page appears.
- Do the following:
- Select one of the following event rule types:
- Event
- Early Event
- Commit Event
- Select the entity to which the rule applies.
- ClickCreate Rule.The event rule page appears. The following image shows theAllocate payments to outstanding ordersevent rule for the Sample API:
- Define the parameters of the rule:Event nameThe name of the event rule.Leave this field blank for the system default.EntityThe name of the entity being acted upon.CodeThe 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);ActiveSelect to activate the rule.Default:ClearedThe API must be complete.
- ClickActivate and Closeto 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:
. Therowrowobject reflects client changes from JSON, and all logic processing. It has attributes for every column, so you can refer to an order'srow.amount_total. It also provides role accessors, so you can refer to an order'srow.customer.balance, or can obtain a collection ofrow.lineitems(a collection of lineitem rows). Rows also provide persistence to read/alter data.For more information about the row object, see Row Objects.
. TheoldRowoldRowobject 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.ThelogicContextobject 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 thelogicContextobject, see The logicContext Object.
- logic.sys.System methods, including theInsertIntoFrom,allocateFromTo, andfindWheresystem 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.
- About defining custom REST resources and row object behavior, see Define Custom REST Resources.
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
object, including how to update an object using thelogicContext
method, see The logicContext Object.touch
- About system methods, see Rule Types.
- About a list of the methods, including JavaScript context variables, see Quick Reference.