Mobile Services server script reference
The feature described in this topic is available only in preview. To use this feature and other new Windows Azure capabilities, sign up for the free preview.
Windows Azure Mobile Services enables you to define custom business logic that is run on the server. This logic is provided as a JavaScript function that is either registered to an insert, read, update, or delete operation on a given table or is assigned to a scheduled job. For example, an insert script for the checkins table is executed each time an item is inserted into that table. Such an insert script is defined as follows:
function insert(item, user, request) { // implementation }
The name of the script must match the type of operation against which it is registered. Note that a delete function must be named del because delete is a reserved keyword in JavaScript. For more information about how to register a script on the server, see Server script example how tos.
This topic includes the following sections:
-
Defining scripts
-
Executing an operation
-
Modifying an operation
-
Overriding success and error
-
State considerations
-
Modules
Defining scripts
A script function that is registered to a table operation always takes three arguments. The second argument is always a User object that represents the user that submitted the request. The third argument is always a Request object, which is used to direct the Mobile Services runtime on what to do after the script executes. Canonical script function signatures are as follows:
| Operation | Signature |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
When you register a script, you can provide alternate names for arguments in function signatures. For more information about how to register a script on the server, see Server script example how tos.
Note |
|---|
| A script that defines a scheduled job has no parameters as it is not provided any data by Mobile Services. For more information, see Schedule recurring jobs in Mobile Services |
Scripts can optionally include helper functions, such as in the following example:
function insert(item, user, request) { if (!item.approved) { handleUnapprovedItem(item, request); } else { request.execute(); } } function handleUnapprovedItem(item, request) { // Implementation }
Note |
|---|
| You must declare all variables in your script. Undeclared variables are not permitted and will cause an error. |
Executing an operation
A script registered to a table operation must implement at least one of the following methods of the Request object to make sure that the client receives a response.
| Method | Description |
|---|---|
|
execute |
The operation is completed as requested and the standard response is returned. |
|
respond |
A custom response is returned. |
Important |
|---|
| These scripts must call execute or respond to make sure that a response is returned to the client. When a script has a code path in which neither of these methods is invoked, the operation may become unresponsive. |
The following script calls the execute method to complete the data operation requested by the client:
function insert(item, user, request) {
request.execute();
}
In this example, the item is inserted into the database and the appropriate status code is returned to the user.
A script can also override the default response behavior. This is done by calling respond instead of execute and writing the response to the client, as in the following example:
function insert(item, user, request) { if (item.userId !== user.userId) { request.respond(statusCodes.FORBIDDEN, 'You may only insert records with your userId.'); } else { request.execute(); } }
In this example, the request is rejected when the inserted item does not have a userId property that matches the userId of the current user. In this case, a database operation (insert) does not occur, and a response with a 403 HTTP status code with a custom error message returned to the client.
Modifying an operation
When the execute method is called, the item, query or id value that was passed as the first argument into the script function is used to perform the operation. For an insert, update or query operation, you can modify the item or query before you call execute, as in the following examples:
function insert(item, user, request) { item.scriptComment = 'this was added by a script and will be saved to the database'; request.execute(); } }
function update(item, user, request) { item.scriptComment = 'this was added by a script and will be saved to the database'; request.execute(); }
function read(query, user, request) { query.where({ userid: user.userId}); // Only return records for the current user request.execute(); }
Note |
|---|
| In a delete script, changing the value of the supplied userId variable does not affect which record gets deleted. This means that, in effect, a delete operation cannot be modified. |
Overriding success and error
By default, the execute method writes responses automatically. In some cases you may want to modify the results of a query before writing those results to the response. You can do this by using passing in a success handler when you call execute. The following example calls execute({ success: function(results} { … }) to preform additional work after data is read from the database but before the response is written:
function read(query, user, request) { request.execute({ success: function(results) { results.forEach(function(r) { r.scriptComment = 'this was added by a script after querying the database'; }); request.respond(); } }); }
When you provide a success handler to the execute method, you are responsible for letting the runtime know that you script has completed and that a response can be written. You do this by calling the respond method. When you call respond without passing any arguments, Mobile Services generates the default response.
Note |
|---|
| You can only call the respond method without arguments to invoke the default response after first calling the execute method. |
The execute method can fail for a variety of reasons, including loss of connectivity to the database, an invalid object, or an incorrect query. When such an error occurs, Mobile Services writes an error to the response. Because Mobile Services provides default error handling for scripts, you do not need to handle such errors that may occur in the service. You can also provide for custom error handling in your scripts. Do this by defining an error handler to the execute method, as in the following example:
function update(item, user, request) { request.execute({ error: function(err) { // some custom logging request.respond(); } }); }
When you provide an error handler to the execute method, Mobile Services returns an error result to the client when respond is called.
State considerations
Mobile Services does not preserve state in script operations. Every time a script executes, a new global context is created in which for the script is executed. Do not define any state variables in your scripts. If you need to store state from one request to another, create a Mobile Services table in which to store your state, and then use the Table object or the mssql object to read and write your state to the table.
Modules
Mobile Services exposes a set of modules that scripts can require. For example, a script can require 'request' to do HTTP requests:
function update(item, user, request) { var request = require('request'); request('http://www.google.com', function(err, response, body) { ... }); }
Some of these modules are part of Node.js while others (such as request) are additional modules that are included for your convenience. The following modules can be accessed from your scripts by using the require function:
| Module name | Description |
|---|---|
|
apns |
Exposes functionality of the Apple Push Notification Service (APNS) to send push notifications to iOS apps. This functionalty is also available in the apns object, which is accessed from the apns property of the global push object. For more information, see Get Started with Push Notifications. |
|
azure |
Exposes the functionality of the Windows Azure SDK for Node.js. For more information, see the Windows Azure SDK for Node.js. |
|
mpns |
Sends push notifications to Windows Phone 8 apps by using the Microsoft Push Notification Service (MPNS). This functionalty is also available in the mpns object, which is accessed from the mpns property of the push object. For more information, see Get Started with Push Notifications. |
|
request |
Sends HTTP requests to external REST services, such as Twitter and Facebook. For more information, see Send HTTP request. |
|
sendgrid |
Used to send email by using the Sendgrid email service. For more infoirmation, see Send email from Mobile Services with SendGrid. |
|
wns |
Sends push notifications to Windows Store apps by using the Windows Notification Service (WNS). This functionalty is also available in the wns object, which is accessed from the wns property of the global push object. For more information, see Get Started with Push Notifications. |
All other Node.js modules are disallowed and attempting to require any of those results in a runtime error.
In This Section
See Also
Note
Important