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 (), the previous row (row
), and any parent rows. Event rules can begin with the incoming request, the final response, and early- and post-commit processing on a transaction.oldRow
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
method.logicContext.save() - 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 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 by amountTotal.
- ChangeOrder.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 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
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:
| Defines database column:
|
CA Live API Creator | Watches for changes:
| Watches for changes:
|
Reacts to changes:
| Reacts to changes:
|
Create Event Rules
- In the Manage section, clickRules.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.
- ClickCreate a Rule.
- Do the following:
- 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, selectEarly Event,Commit Event, orPreinsert Event. - Select the entity to which the rule applies.
- ClickCreate Rule.
- Define the parameters of the rule, and then clickActivate and Close:TitleThe title for the event rule. The title for rules does not affect logic processing. To apply a default value, leave this field blank.Required:NoEntityThe name of the entity being acted upon.TopicsThe topic that you want to associate to this rule.For more information about topics, see Manage Topics.CodeThe 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 haveCA Live API Creatorreturn 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 theSysUtilityJavaScript object'sdatabaseNowDeferred()method or thesqlSnippetDeferred()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);ActiveSelect to activate the rule.Default:ClearedThe API must be complete.AsynchronousSelect this checkbox to haveCA Live API Creatorexecute 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.NameThe 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:
androw
. TheoldRowrowobject reflects client changes from JSON, and all logic processing. TheoldRowobject 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 thelogicContextobject methods to read/write other rows.For more information about this object, see The logicContext Object.
- Logic services.You can use theSysLogicobject 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.