Sencha Inc. | HTML5 Apps

Blog

Sencha and Backend REST Services: How Modus Create Connects an App to DreamFactory

September 05, 2013 | Todd Appleton

Guest Blog Post

Introduction

DreamFactoryIf you're reading this article, then you probably already know the power of Sencha Touch and Ext JS for building web apps. But what are the options for the backend? As the mobile app space continues to heat up, a great way to host and manage your apps is to use a backend services platform that provides a REST API. This virtually eliminates the need for costly server-side development allowing you to focus on building great apps.

In this post, I'm going to introduce you to how Modus Create connects their corporate address book app, built using Sencha Touch 2 and Ext JS 4, to the DreamFactory open source backend services platform. We call each instance of the DreamFactory platform a 'DSP' which is short for DreamFactory Services Platform. As you will see, each DSP provides a database and a full-featured REST API that help to simplify the app building process.

App Overview

Modus Create had an existing address book app and wished to make some enhancements and port it to use DreamFactory for the backend. The desktop version of the address book uses Ext JS and is intended to serve as a console for managing contacts and groups. The mobile version uses the Sencha Touch 2 framework with different profiles for phone and tablet. Below are some screenshots from each device.

DreamFactory

The desktop UI for managing contacts and groups consists of two tab panels with a custom schema grid component. The schema grid works with the backend to provide CRUD operations and optionally the filtering in the upper right.

DreamFactory DreamFactory

The phone version's main screen shows all contact groups using a dataview list. Selecting All Contacts displays the entire list of contacts, again using a dataview list. It also features grouping and an index bar on the right.

DreamFactory

Selecting a single contact shows the details for that contact. This is an Ext container with custom tpl. Clicking on a link will launch the appropriate app or make a phone call.

DreamFactory

The tablet version shows groups and contacts on left, contact details on right. It uses the same components as the phone version, but with a different profile for tablet.

The complete source code for this app is available on GitHub. Here you will find a README file with lots of relevant information about the app which I won't duplicate here. The basic layout of the code is that /docroot/index.html has JavaScript to detect device type and redirect to /desktop/index.html or /mobile/index.html. These are the entry points for the Ext JS and Sencha Touch apps, respectively.

For this post, we're going to focus on the code that communicates with the REST API. There is a class common.DreamFactory defined in /docroot/common/DreamFactory.js that provides nice wrapper functions for the DreamFactory API. This class works for both Sencha Touch and Ext JS. To get familiar with how this works, let's take a look at how to authenticate and make a database query.

Log In (POST /rest/user/session)

When the app starts up, you'll be prompted to log in. This results in a call to common.DreamFactory.login().

 
login : function (email, password, callback) {
            rpc({
                url     : 'user/session/',
                params   : {
                    email : email,
                    password : password
                },
                callback : callback
            });
        }
 
POST
https://dsp-test.cloud.dreamfactory.com/rest/user/session/
 

This function simply calls the utility function rpc() passing it the relative URL for the login request as well as the email and password entered by the user. rpc() then calls Ext.Ajax.Request() passing it the URL to POST to and the data to be sent. The base URL (the part before /rest) is based on the name you gave your DSP when you created it. The callback is invoked when the request has completed allowing for the usual success and error handling.

 
function rpc(config) {
        var method = config.method,
            headers = {
                'X-Application-Name' : 'add'
            };
 
     // if REST tunneling is required, then uncomment the following lines
//      if (method === 'DELETE' || method === 'MERGE') {
//          headers['X-HTTP-METHOD'] = method;
//          method = 'POST';
//      }
 
    Ext.Ajax.request({
        url     : common.DreamFactory.serviceUrl + 'rest/' + config.url,
        method   : method,
        headers  : headers,
        jsonData : config.params,
        success  : function (response) {
            var o = Ext.decode(response.responseText);
            if (config.callback) {
                config.callback(o);
            }
            else {
                console.dir(o);
            }
        },
        failure  : function (response) {
            var o = Ext.decode(response.responseText);
            console.dir(o);
            if (config.callback) {
                config.callback(o);
            }
        }
    });
}
 

One key step is adding the HTTP header 'X-Application-Name' or preferably 'X-DreamFactory-Application-Name' with the value set to the app's API name as defined when the app was created in the DreamFactory admin console. In our case, the app name is 'add' so we have:

 
'X-DreamFactory-Application-Name' : 'add'
 

On successful login a session_id will be returned. Future requests can set a header value equal to this session id such as:

 
'X-DreamFactory-Session-Token : 'ps72mgce0ul2vj5apv6q8sntr8fne2je'

or rely on browser cookies to handle it. If you don't want to require users to log in, you can set up a ‘Guest’ role in the system that gives access to the API without authentication.

Retrieving Contacts (GET /rest/db/Contacts)

Now that we have logged in, we can access the database to retrieve the list of contacts. There's a function named common.DreamFactory.filterRecords() that handles this request. Setting the filter param to empty means return all records, or you can specify a filter string such as "firstname='bob'". There are other options which are pretty self explanatory once you look at the code that builds the query. All of the options are documented in the live API docs inside the DSP admin console. As with login(), filterRecords() calls rpc() to make the actual AJAX request.

 
filterRecords : function (table, options, callback) {
            var url = 'db/' + tableName(table),
                args = buildQuery(options);
 
        if (args.length) {
            url += '?' + args.join('&');
        }
 
        rpc({
            url     : url,
            params   : options.params,
            callback : callback || options.callback
        });
    }
 
GET
https://dsp-test.cloud.dreamfactory.com/rest/db/Contacts?include_count=true&filter=&offset=0&limit=25
 

There are other CRUD functions such as createRecords, updateRecords, and deleteRecords. Please see /docroot/common/DreamFactory.js for details on each of these functions.

Log Out (DELETE /rest/user/session)

To log out you just need to delete the session that was created for you. Don't forget the X-DreamFactory-Application-Name header.

 
logout : function (callback) {
            rpc({
                url     : 'user/session/',
                method   : 'DELETE',
                callback : callback
            });
        }
 
DELETE
https://dsp-test.cloud.dreamfactory.com/rest/user/session
 

Schema Management

You can import JSON schema into your DSP using the Manage Schema tab in the admin console. This is how the schema for the address book app was created. There are Contacts, Contact Infos, Contact Groups, and Contact Relationships. Each contact can have one or more contact infos (home, work, etc). Each contact is linked to its parent groups using contact relationships. See /schema for the JSON files that define the schema for this app. The API provides some nice features like the ability to include child records in the results of queries on the parent object, change the children, then update all children with a single API call.

Resources

If you're building a Sencha app, think about whether using a backend services platform with REST might work for you. We've just covered a small part of what's available in the DreamFactory backend. Other services are available for NoSQL data, binary documents, user permissions, and external services. For more information or to try it out for free, please see the following links. Thanks for reading and good luck with your apps!

  • General information and documentation
  • Sign up for a DreamFactory account and manage your DSPs
  • DreamFactory blog has helpful posts about getting started with DreamFactory. There are articles on CORS, NoSQL support, API basics, integrating external services and much more!
  • Detailed description of the Sencha Touch To Do List app that comes with each new DSP.
  • To experiment with the REST API, you can go to the API Documentation tab in the admin console. This offers live API docs built with Swagger.

There are 3 responses. Add yours.

kumarverma

1 year ago

I am awe struck! amazing application.

mosesfaith

1 year ago

Great

Tom Coulton

1 year ago

We translated this blog article and posted it here: http://www.xenophy.com/sencha-blog/8750

This is also the link for the Japan Sencha User Group: http://www.meetup.com/Japan-Sencha-User-Group/

Comments are Gravatar enabled. Your email address will not be shown.

Commenting is not available in this channel entry.