Dan Flict Dan Flict - 5 months ago 60
Node.js Question

Insert in a different table in Azure table script for Azure Mobile Apps

I've been searching extensively for this answer but only found solutions referring to the old Azure App Services instead of the new Azure Mobile Apps.

In this exemple, in the Table Scripts of a table, I'm inserting the authenticated user id into the userID field of that same table.

table.insert(function (context) {
context.item.userId = context.user.id;
return context.execute();
});


But if also want to insert it in a different table from the one the user has asked to insert? How can I access this other table from the Table Scripts?

Before, as shown on all solutions I found, you could do "tables.getTable('otherTable')" to access another table from the same SQL DB. But now I get an error.

Reading the 'Azure Mobile Apps - Node SDK' documentation, I found the "context.tables()" function, that appears to obtain a different table from the db. But when I insert using the code bellow nothing happens:

table.insert(function (context) {
var table2 = context.tables('table2');
table2.insert({string_column: '1234'});
return context.execute();
});


Thanks!

Answer

Found out the correct way of doing it. Here is my code:

var insertMiddleware = function(req,res,next){

    var table2 = req.azureMobile.tables('table2');
    var toBeInserted = {field1: 'something',
                        id: '1'}; //id is needed 

    var promiseReturned = table2.insert(toBeInserted);
    promiseReturned.then(function(data){
        console.log('Inserted with success!');
        next();
    }, function(error) {
        console.log('Found an error', error);
    });
};

table.insert.use(insertMiddleware, table.operation);

table.insert(function (context) {
   return context.execute();
});

First I declare a middleware function that will be executed every time the insert is called. In it I call the insert function from the table I want to access, and it returns a promise. (that was my error)

Then I associate the middleware with the insert function of the table where the script is running using the "use" function.

Finally I run the insert function normally.