Transactional operations
Apstrata allows you to run multiple operations on the documents of your store within transactional boundaries. When executing operations in a transaction, Asptrata "write-locks" the corresponding documents and applies the effect of the operations as soon as the transaction is committed (i.e. validated), or discards it if the transaction is rolled-back (i.e. invalidated). Transactions can be created from within your Apstrata server-side scripts or from the client side, by invoking the Transaction API, however, it is preferable to only create them in your scripts.
Back to the map Next station: set permissions
Example: create a new game instance and save the player's name and location
You are developing a cool mobile game. Let us imagine that whenever a player creates a new instance of this game, you would like to save the instance status and the player's name and location in two distinct documents. However, you also need to make sure that both documents get created together, so you do not end up with orphan games. Let us see how to do this using an Apstrata script.
... // Retrieve the player's name and location from the request var location = request.parameters.location; var player = request.parameters.player; // Prepare the parameters to send to the SaveDocument API in order to save // the player's data. Note that we use the player name as the document key var playerParams = { "apsdb.store": "DefaultStore", // "DefaultStore" is the name by default. If you did not rename your store, this line is optional "location": location, "location.apsdb.fieldType": "geospatial", // we specify that the "location" field is of type "geospatial" "player": player, "apsdb.documentKey": player } // Prepare the parameters to send to the SaveDocument API in order to save // the game data. var gameParams = { "apsdb.store": "DefaultStore", // If you did not rename your store, this line is optional "player": player, "score": 0, "level": 0, "lives": 0, "score.apsdb.fieldType": "numeric", "level.apsdb.fieldType": "numeric", "lives.apsdb.fieldType": "numeric" } var transaction = null; try { // Create a new transaction transaction = apsdb.beginTransaction(); // Invoke the SaveDocument API to save the player's data var response = apsdb.callApi("SaveDocument", playerParams, null); // the response JSON object contains the "key" field, document key of the created document if (response.metadata.status == "failure") { throw response.metadata; } // Invoke the SaveDocument API to save the game data response = apsdb.callApi("SaveDocument", gameParams, null); // the response JSON object contains the "key" field, document key of the created document if (response.metadata.status == "failure") { throw response.metadata; } // Commit the transaction transaction.commit(); return "Successfully created the game"; }catch(exception) { // If the transaction exists, roll it back if (transaction) { transaction.rollback(); } return exception; }
Dig deeper
Related tutorials