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.
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.
Layer7 Live API Creator
invokes event logic as it processes row inserts, update requests, or delete requests.
Layer7 Live API Creator
de-aliases resource updates onto the underlying base table objects.
Layer7 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,
Layer7 Live API Creator
ignores that value.
Event rules provide
Layer7 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
Layer7 Live API Creator
Fires the Event Rule
Event rules interact with other logic.
Layer7 Live API Creator
fires them at predetermined times during logic execution. The time when
Layer7 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 the
    logicContext.save()
    method.
  • Early event.
    Fires before it executes your logic.
    Layer7 Live API Creator
    does not subjects the row data to formula rules and other derivation rules. You can change the rows and
    Layer7 Live API Creator
    subjects 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 have
    Layer7 Live API Creator
    generate an alphanumeric primary key using a pre-insert event rule that computes the keys. You can also have
    Layer7 Live API Creator
    compute a non-nullable attribute before inserting a row into the table using a pre-insert event rule.
    Database-generated primary keys do not require pre-insert event rules. The database handles these keys automatically.
    For more information about how to compute an alphanumeric primary key with sequences, see Oracle Sequence Example API Sample.
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.
Layer7 Live API Creator
executes event rules when it calls table-based resources. Resource events are pieces of JavaScript that
Layer7 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:
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 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,
Layer7 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)
Layer7 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 an Event Rule
Prerequisite:
Your API is connected to an active database that contains at least one table or view.
Follow these steps:
  1. In the Create 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
      • Pre-Insert Event
      If you want to change primary keys within an event, select
      Early Event
      ,
      Commit Event
      , or
      Pre-Insert 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 that
    Layer7 Live API Creator
    is acting 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 JavaScript Code Examples.
    You can have
    Layer7 Live API Creator
    return 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 the
    SysUtility
    JavaScript object's
    databaseNowDeferred()
    method or the
    sqlSnippetDeferred()
    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 the
      ComplianceReporting
      resource, using the
      SysUtility.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 the
    Controlled Substance Reporting
    event rule in the
    Sample
    API.
    Active
    Select to activate the rule.
    Default:
    Cleared
    The API must be complete.
    Asynchronous
    Select this checkbox to have
    Layer7 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 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:
  • row
    and
    oldRow
    . The current row (the
    row
    object) reflects client changes from JSON, and all logic processing. The previous row (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. 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 the
    logicContext
    object.
    For more information about this object, see The logicContext Object.
  • Logic services.
    You can use the system methods that are included with the
    SysLogic
    object in validation rules, formula rules, and event rules.
    For more information:
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
Layer7 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.
Layer7 Live API Creator
must ensure that it executes your validation logic after you make changes. Database validations apply to event rules.
Layer7 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.