Monday, January 11, 2016


Building a commercial Node.js user interface – some do’s and don’ts

If you want to develop Node.js applications coming from a PHP background, the following are some considerations as I have found them. For software developers who were writing user interface in languages such as PHP, writing model->view->controllers comes easy along with a host of useful widgets and controls. For example, Yii framework in PHP makes it elegant and performant to write such web applications. Common server side functionality includes connecting to a database and making API calls. Javascript validation is still used but the inline html execution along with the /var/www/ copy-deployment makes PHP different and easy for UI development.

With Node.js, the language is javascript and if we are familiar with the asynchronous programming model on the client side as is the case with client side scripts in PHP, then this is no different. The server side framework comes with rich templates and parsers such as Hogan/moustache and express for rendering the views. But here are some of the UI artifacts we would like to carry forward:

1)      Templates and variables as output from the controller to the view
we have fine control over the html we can send in the response. For example:
res.render('index', servers, function(err, html) {
             insertion = "<tr><td>{{ server.pk }}</td><td>{{ server.fields.server_id }}</td></tr>";
       var template = Hogan.compile(insertion);
       data = '';
       servers.forEach(function(server, index, array){
            var row = template.render({'server':server});
            data += row; 
             });
      var h = html.replace('LIST_OF_SERVERS', data);
      res.setHeader('Content-Type', 'text/html');
      res.send(h);
});

2)      Flash as a notification to the user for error and info
       req.flash('info', '%s items have been saved.', items.length);

3)      Session as a validation that the user is currently signed in

require('./saml/saml')(app);
function secure(req,res,next){
      // Check session
      if(req.session.currentUser){
        next();
      }else{
        app.settings.saml.startAuth(req, res);
      }
    }
app.all('/', secure); 

4)      Css and layouts as an organization and theme across views
<link rel="stylesheet" type="text/css" href="../stylesheets/screen.css" media="screen, projection" />
<script type="text/javascript" src="../javascripts/jquery.js"></script>

5)      Redirect and rendering  as appropriate

app.get('/', function (req, res){
  res.redirect(login_url);

});

6) Exception handling : Use appropriate state handlers such as the error: and success: in $.post calls and you should have less try-catch-finally to use

7) Logging: You can continue to use a logger that logs to a file

No comments:

Post a Comment