Event Rule Types
Event rules are server-side JavaScript-code business logic that can begin with the incoming request, the final response, and early- and post-commit processing on a transaction. invokes event logic as it processes row inserts, update requests, or delete requests. de-aliases resource updates onto the underlying base table objects. reuses event rules over the resources that are built on the table. Event rules do not have to return a value. If they do, ignores that value.
lac52
Event rules are server-side JavaScript-code business logic that can begin with the incoming request, the final response, and early- and post-commit processing on a transaction.
CA Live API Creator
invokes event logic as it processes row inserts, update requests, or delete requests. CA Live API Creator
de-aliases resource updates onto the underlying base table objects. CA Live API Creator
reuses event rules over the resources that are built on the table. Event rules do not have to return a value. If they do, CA Live API Creator
ignores that value.Event rules provide
CA Live API Creator
access to external/reusable JavaScript functions by way of the Nashorn JavaScript engine.You can create event rules that:
- Insert (audit) changes for the current entity (table or view).
- 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
CA Live API Creator
Fires the Event RuleEvent rules interact with other logic.
CA Live API Creator
fires them at predetermined times during logic execution. The time when CA Live API Creator
fires the event rule depends on the event rule type:- Event.Fires after it completes the row logic. 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 thelogicContext.save()method.
- Early event.Fires before it executes your logic.CA Live API Creatordoes not subjects the row data to formula rules and other derivation rules. You can change the rows andCA Live API Creatorsubjects the changes to validations, other chained logic, and saves the changes.
- Commit event.Fires after it completes row logic for all the rows in the transaction. The rows reflect logic processing. You cannot change the rows.
- Pre-Insert event.Fires before it sends the row to the database on insert. You can haveCA Live API Creatorgenerate an alphanumeric primary key using a pre-insert event rule that computes the keys. You can also haveCA Live API Creatorcompute a non-nullable attribute before inserting a row into the table using a pre-insert event rule.
For more information about logic execution, see Logic Execution.
Event Rules vs. Resource Events
Event rules reduce the amount of code that you must write. They require that you transition to "think spreadsheet". Event rules are a complement to the other declarative forms of rules, address issues that other rules do not address, and have unlimited flexibility.
CA Live API Creator
executes event rules when it calls table-based resources. Resource events are pieces of JavaScript that CA Live API Creator
executes for each row. You define them for GET calls or for PUT/POST calls.Create event rules before creating resource events.
For more information:
- About resource events, see Manage Resource Events.
- About the "think spreadsheet" concept, see Logic Patterns.
Think Spreadsheet Rules Example
The following "think spreadsheet" rules example is a common example of the code for 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 API deveopers 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 an Event Rule
Prerequisite:
Your API is connected to an active database that contains at least one table or view.Follow these steps:
- In the Create 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 theBy entitytab 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
- Pre-Insert Event
If you want to change primary keys within an event, selectEarly Event,Commit Event, orPre-Insert 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 thatCA Live API Creatoris acting 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 JavaScript Code Examples.You can haveCA Live API Creatorreturn an object and assign it to an entity resource 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 1:A typical example is an auditing event. This example uses of the current/old row in making your logic conditional:if (row.amount_total != oldRow.amount_total) SysLogic.insertChildFrom("purchaseorder_audit", logicContext);Example 2:The following example is an event rule that uses the current/old row to verify the condition of the product and do the following:
- Create a JSON string, per the format of theComplianceReportingresource, using theSysUtility.getResource()method.
- Post or send the JSON string to a message queue (this is not shown in the code).
if (row.name == "Dynamite" && row.total_quantity_ordered != oldRow.total_quantity_ordered) { log.debug("***controlled substance - notify authorities"); var json = JSON.parse(req.json); // convert req's JSON string to JSON objects var custName = json.customer; // get the name from the request var options = { sysfilter: "equal(name:'" + custName + "')" }; var custAccount = SysUtility.getResource("ComplianceReporting", options); // get resource JSON log.debug("***sending compliance message" + JSON.stringify(custAccount[0]));}This code is from theControlled Substance Reportingevent rule in theSampleAPI.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 to accept the default.
The event rule is created. The list of rules display.
Use Event Rules
The logic engine invokes the following variables on every update, providing key contextual information:
- rowandoldRow. The current row (therowobject) reflects client changes from JSON, and all logic processing. The previous row (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. Event rules can also access the values of any parent rows.For more information about row logic, see Logic Execution.
- Logic context.You can read/write other rows using the system methods that are included with thelogicContextobject.For more information about this object, see The logicContext Object.
- Logic services.You can use the system methods that are included with theSysLogicobject in validation rules, formula rules, and event rules.For more information:
- About this object, see The SysLogic Object.
- About event context, see the "Event Context" section.
Change Primary Keys within an Event Rule
You can change primary keys within an event rule by defining the change only within the code of an early, commit, or pre-insert event rule.f
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 invoke other JavaScript methods, including systems-supplied ones, within your event rule.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.