Sencha Inc. | HTML5 Apps

Blog

Writing an Ext.Direct Backend in Node.js

January 08, 2014 | Juris Vecvanags

Some of you may have tried it, but there are still many developers who haven’t used this hidden gem — Sencha Ext.Direct. It was announced in 2009 and named one of the best features introduced in Ext JS 3.0.

In this article, we will introduce you to Ext.Direct and provide examples of an Ext.Direct connector and backend for Node.js.

Why You Should Consider Ext.Direct

In essence, Ext.Direct is a language and platform agnostic technology to communicate between client and server. All calls are initiated from the client-side and offer features that make coding fun again. I love to call it RPC on steroids. The most important feature is that Ext.Direct is bundled with Ext JS, so you don’t need any extra libraries on the client-side to get it running. You also have the ability to retry calls, upload files and batch transactions. You can find the full specs here.

Ext JS is server-side agnostic, so you can consume a wide range of web services. That’s why it’s such a powerful client-side framework. The most popular ways to communicate are REST, regular Ajax calls using JSON or XML data and JSONP. Although these are indeed popular and widely used, there are times when you want a more flexible and framework-friendly stack. This is where Ext.Direct shines.

Ext.Direct is used to call exposed or predefined server-side methods. The beauty is that calling any server-side procedure feels like executing any other JavaScript method locally. For example:

ExtRemote.DXStaff.create({firstName:’John’,lastName:’Smith’});

You don’t have to think about what’s in between and how to treat the backend. It’s just another object with methods you can call and get a response, regardless of whether it’s a data selection from a database or a mathematical computation. Another benefit of Ext.Direct is the very tight integration with data stores and forms. In this case, all you have to do is specify endpoint methods for CRUD actions and load/submit methods for the forms.

With Sencha Touch 2.3, Ext.Direct specs are now fully implemented with support for forms along with CRUD functionality for data stores. The same syntax can be applied for both Ext JS and Sencha Touch. Extensive documentation is provided as part of the following examples and backend connector as well as in the Sencha docs.

Current Server-side Stacks

Now, let’s look at the server-side. You may wonder whether you can leverage Ext.Direct, if your company is running PHP or Java. Ext.Direct comes with a simple implementation in PHP, and there are lots of other implementations available that are supported by our community members. For example, there are Java, Perl, Ruby, .NET, ColdFusion and Python implementations to name a few. Recently, we got a new addition to this growing list — a backend for Node.js.

Ext.Direct Connector and Backend for Node.js

If you plan to adopt Node.js for your backend solution and would like to try Ext.Direct features, you will need the Ext.Direct Connector for Node.js. It can be found in the npm repository here. You can download and install it via npm or grab the source code from github.

To help you get started, we created an extensive set of examples that you can find here. They cover the most common scenarios and widgets that our frameworks support.

In order to make it easier for developers who are not familiar with writing a Node.js backend, we also provided a full-featured web server to serve static content. As for database choices, we supplied both MySQL and MongoDB examples as well as a client for Ext JS 4.2.x and Sencha Touch 2.3.x.

The backend provides the following features:

  • API auto-discovery
  • Flexible server port
  • logging
  • Development / Production environment
  • Ext.Direct router and static page serving
  • File upload
  • Session support
  • CORS support
  • Flexible response headers and age
  • Both http and https protocols

After you download the Node.js backend, you will have to configure it. If you’re using MySQL, you will also have to import the DB schema (optional and used only for examples). Unless you plan to make any changes to the server scripts, everything you need can be configured from the two scripts named server-config.json and db-config.json. Once you’ve configured them, run this command in the terminal:

npm install

This will install all of the required modules and dependencies.

Let’s take a closer look at config options for Ext.Direct, as all of the others are self-explanatory.

 
"ExtDirectConfig": {
   "namespace": "ExtRemote", // Direct namespace
   "apiName": "REMOTING_API", //Direct API name (both entries should match at client side)
   "apiPath": "/directapi", // URL endpoint where API will be served
   "classPath": "/direct", //location of your Ext.Direct classes
   "classPrefix": "DX", // For advanced cases,You may have multiple class instances in the same folder, this way you can separate and list prefixed classes only
   "server": "localhost", //RPC server domain
   "port": "3000", //RPC server port
   "protocol": "http", // [http|https] 
   "appendRequestResponseObjects": true //if true, every API call will receive full request and response objects as part of the argument list
}
 

Now that your server is configured, you can start it up: issue this command from the terminal (we assume that you’ve already installed the Node.js server):

node server.js

By default, the server is configured to respond to requests via port 3000. If you intend to serve from port 80 (standard http), you have to change that inside the config file and run the server with superuser privileges.

sudo node server.js

If you plan to serve the application from the same server, then place its files inside the /public folder.

This is what the simplest HelloWorld API method would look like:

 
var DXHello = {
    wave: function(params, callback){
        callback({
            success:true,
            msg:'Hello world',
            params: params
        });
    }
};
 
module.exports = DXHello;
 

You can call this method from both Ext JS and Sencha Touch using the same syntax:

 
ExtRemote.DXHello.wave(‘Hi!,
    function(res){
        console.dir(res);
    }
);
 

This is what the common function signature would look like:

 
// method signature has 5 parameters
    /**
     *
     * @param params object with received parameters
     * @param callback callback function to call at the end of current method
     * @param sessionID - current session ID if "enableSessions" set to true, otherwise null
     * @param request only if "appendRequestResponseObjects" enabled
     * @param response only if "appendRequestResponseObjects" enabled
     */
    happyNewYear: function(params, callback, sessionID, request, response){
 
	// Your code here
}
 

We hope you find the examples useful. Try them out and share your feedback with us on the Sencha forum. Happy coding!

There are 5 responses. Add yours.

Joris

3 months ago

Sweet!! I would love to see another post that explains how to interact with models/stores.

dcima

3 months ago

Very interesting topic.

I’m trying your examples and everything it’s working fine except the FormFileUpload on some browsers.

It works ok on Chrome (32.0.1700.76m), Safari (5.1.7.7534.57.2), Opera(12.16.1860)
but on Firefox (26.0) and IE (11.09.9431) has a strange behaviour:

the first time that i select a file from local file system clicking on the “Select Photo…” button produces no effect and the filesubmit event is not fired on server.

Following selections are ok.

I’m using ext-4.2.2.1144 on server (Ubuntu 13.04) with client Windows 7 64 bit SP1.

No problems with the upload examples of the framework (ext-4.2.2.1144/examples/form/file-upload.html).

Tom Coulton

3 months ago

We’ve translated this blog article into Japanese here: http://www.xenophy.com/sencha-blog/10056

Also, just so you know this is the Sencha Japan User Group: http://www.meetup.com/Japan-Sencha-User-Group/

Sebastian

3 months ago

Great post, but if someone is interested in a little bit deeper overview, here (http://devjs.eu/en/sencha-touch-and-node-js-fully-functional-backend-with-ext-direct-support/) I described how to combine Ext.Direct with moongose, some unit test tools and simple ST app.

Juris

3 months ago

@dcima We have identified a cause and it will be fixed in 4.2.3

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

Commenting is not available in this channel entry.