Export (0) Print
Expand All

Read and write data

Updated: April 15, 2014

In a JavaScript backend mobile service, you use the tables object to work with data stored in a SQL Database from server scripts. In a table operation, the tables object is a global.

In the following example, the global tables object is used to access the permissions table, which is queried to determine if the user is authorized to create a new order.

function insert(item, user, request) {
    var permissionsTable = tables.getTable('permissions');

    permissionsTable.where({
        userId: user.userId,
        permission: 'submit order'
    }).read({
        success: checkPermissions
    });

    function checkPermissions(results) {
        if (results.length > 0) {
            // Permission record was found. Continue normal execution.
            request.execute();
        } else {
            console.log('User %s attempted to submit an order without permissions.', user.userId);
            request.respond(statusCodes.FORBIDDEN, 'You do not have permission to submit orders.');
        }
    }
}
noteNote
Note: we recommend setting permissions to Only Authenticated User when using the userId property. Otherwise, your code must handle undefined values that are returned for unauthenticated users. For more information, see Get started with users in Mobile Services.

In a custom API, the tables object is obtained from the supplied request.service object, as in the following GET method.

exports.get = function(request, response) {    
    var myTable = request.service.tables.getTable('permissions');
    // Do something with the table here…
};

In the following example, a new record is inserted into the audit table every time an item is updated.

function update(item, user, request) {
    request.execute({
        success: insertAuditEntry
    });

    function insertAuditEntry() {
        var auditTable = tables.getTable('audit');
        var audit = {
            record: 'checkins',
            recordId: item.id,
            timestamp: new Date(),
            values: JSON.stringify(item)
        };
        auditTable.insert(audit, {
            success: function() {
                // Write to the response now that all data operations are complete
                request.respond();
            }
        });
    }
}

For more information, see the Mobile Services script reference

Show:
© 2014 Microsoft