Transactions — JazzRecord JavaScript ORM Documentation

JazzRecord provides the capability to wrap a set of operations (finders, schema changes, etc) inside a transaction. The benefit of doing this is that if any one portion of the transaction fails, all operations are rolled back to the previous state. This is imperative for any sort of financial transactions or similarly vital work.

To run operations in a transaction, simply wrap your code in a call to JazzRecord.runTransaction() and at any point a rollback should be performed due to failure during the transaction, simply throw an excaption.

JazzRecord.runTransaction() takes 2 parameters: a function to run, and an optional context to bind to the function for referencing a new this object.

For example:

JazzRecord.runTransaction(function() {
  var amtToTransfer = 100000;
  var fromAct = Account.findBy("account_number", 1234)
  var toAct = Account.findBy("account_number", 9999);

  fromAct.balance -= amtToTransfer;
  toAct.balance += amtToTransfer;

  if(fromAct.balance < 0)
    throw("From account balance cannot go below 0");

  fromAct.save();
  toAct.save();
});

This code will prevent any account from ever becoming overdrawn. More elaborate code may be necessary to allow your code to handle failed transactions gracefully.