Creating tables and scripts

The first step to implement a web service in Azure Mobile Services is to create a new table. By default, Azure Mobile Services uses a feature called dynamic schema with its SQL database. When you insert a row from the client, new columns are dynamically added to the table. This prevents you from having to create the database schema manually and is a nice code-first approach to developing your backend database. You can always connect to the SQL database manually to fine tune things or make manual changes to the schema.

Return to the management portal, select your mobile services instance, and perform the following steps:

  1. Click on the Data tab.
  2. Click on the Create button found at the bottom center of the page.
  3. Enter User as the table name.
  4. Leave everything else to its default value and click on the Save button.
  5. Repeat this process to create three more tables named Friend, Message, and Conversation.

Now that we have our four tables, we need to create a script to facilitate the login process for the users in our app. Azure Mobile Services allow you to add custom logic to your tables by creating JavaScript scripts that run in Node.js. You can override what happens to each table during the insert, read, update, or delete operations. In addition, you can also create scripts that are completely freeform if you need other custom logic.

Click on the User table and then click on the Script tab. Make sure you are viewing the insert operation. By default, your script will be very simple as seen in the following snippet:

function insert(item, user, request) {

  request.execute();

}

Scripts in Azure Mobile Services have three parameters, which are stated as follows:

  • The item parameter: This is the object that the client sends to the service. In our case, it will be the User object we created in the previous chapters.
  • The user parameter: This includes information about the authenticated user. We won't be using this in our examples.
  • The request parameter: This is an object used to run the table operation and send a response back to the client. Calling execute will complete the operation and return a successful response to the client.

We need to modify the preceding script to only insert a new user when that user does not already exist. If the user does exist, we need to make sure the password matches the username. Let's make a few changes to the script as shown in the following lines of code:

function insert(item, user, request) { 
  var users = tables.getTable('user'),
  users.where({ username : item.Username }).read({
    success: function(results) {
      if (results.length === 0) {
        //This is a new user
        request.execute();
      }
      else {
        var user = results[0];
        if (item.Password == user.Password) {
          request.respond(statusCodes.OK, user);
        }
        else {
        request.respond(statusCodes.UNAUTHORIZED, "Incorrect username or password");
        }
      }
    }
  });
}

Let's summarize what we did in the preceding JavaScript:

  1. First we grabbed the user table. Note that you can reference the name of the table using lower or upper case.
  2. Next, we ran a query to pull out any existing users with the where function. We used item.Username, since this matches our User object in C#. Notice how this method is similar to Linq in C#.
  3. If there are no results, we let the request execute normally.
  4. Otherwise, we compare the passwords and return statusCodes.OK if they match.
  5. If the passwords do not match, we return statusCodes.UNAUTHORIZED. This will cause the client to receive an error.

For a complete list of available functions and methods, make sure you check out the server script reference on MSDN at http://tinyurl.com/AzureMobileServices.

From here, just make sure you click on the Save button to apply your changes. Azure Mobile Services also has the option of providing source control for your scripts via Git. Feel free to take advantage of this feature if you want to make changes to the script in your favorite editor locally instead of the website editor.

After this, we need to create one more script. The way XamChat was built earlier in the book, users can add friends by entering their friends' usernames. So in order to insert into the Friend table, we will need to modify the insert script to look up users by their usernames.

Let's modify the insert script for the Friends table as follows:

function insert(item, user, request) { 
  var users = tables.getTable('user'),
  users.where({ username : item.Username }).read({
    success: function(results) {
      if (results.length === 0) {
        //Could not find the user
        request.respond(statusCodes.NOT_FOUND, "User not found");
      }
      else {
        var existingUser = results[0];
        item.UserId = existingUser.id;
        request.execute();
      }
    }
  });
}

This is pretty similar to what we did before; we ran a simple query to load the user table based on the Username value. We merely have to set the UserId value on the new friend object prior to the execution of the request.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.126.5