azure script insert if no record exists else update on server side

azure, azure-mobile-services

Solution

You can use a server side table script to check if a record exists before completing the insert. Here is a example script that checks if any item in the table has a matching 'text' value and if so doesn't do the insert.

function insert(item, user, request) {
    var table = tables.getTable('todoItem');
    table.where({ 
       text: item.text
    }).read({
       success: upsertItem
    });

    function upsertItem(existingItems) {
        if (existingItems.length === 0) {
            request.execute();
        } else {
        item.id = existingItems[0].id;
          table.update(item, {
            success: function(updatedItem) {
                request.respond(200, updatedItem)
            }
          });
        }
     }
 }

Problem

I am developing my first windows phone app with Azure Mobile Services, I am using below code to insert the records into azure ``` await App.MobileService.GetTable<TodoItem>().InsertAsync(todo); ``` What is the best way to check if this is todo item is already exists, insert the data else updating the existing record on server side?

Original source