Node JS – Controllers (Sails JS)

We can auto-generate a new controller by typing “sails generate controller []” from a terminal. For instance we can type:

sails generate controller test action1 action2 action3

to generate a “TestController.js” file like this:

module.exports = {
     action1: function (req, res) {
          return res.json({
               todo: 'not implemented yet'
          });
     },

     action2: function (req, res) {
          return res.json({
               todo: 'not implemented yet'
          });
     },

     action3: function (req, res) {
          return res.json({
               todo: 'not implemented yet'
          });
     }
};

The controller is generated inside the “controllers” folder. Is however possible to have subfolders, whose controllers will be automatically bound (and referred) with the corresponding subpath.

A controller’s behaviour is quite usual, we can return the default view (or a different one if we specify it with a parameter) by writing:

action2: function (req, res) {
     return res.view();
}

The default view is normally located under “views//.ejs”, so in this case will be under “views/test/action2.ejs”. Here is an example about what it can contain:

<h1>
     action 2
</h1>
<h2>
     this is raw html <%-'<button>button</button'%>
</h2>

By default every view in injected inside the general layout defined in the “views/layout.ejs” file, so we don’t need to define things such the page’s header or title. The place where our view will be rendered inside the layout is specified by “”.


Custom routing + viewModels

Is of course possible to define custom routes by editing the “config/routes.js” file. For instance we can add a new parametrised root that calls the “action3” action of our controller in this way:

'/test/:value/action3': {
     controller: 'test',
     action: 'action3'
}

Then inside our action we can read the parameter and pass it to the view through the viewModel in this way:

action3: function (req, res) {
     var value = req.param('value');

     return res.view({
          receivedValue: value
     });
}

Finally here is how to render something from the viewModel in the view:

<h1>
     action 3
</h1>
<h2>
     the received value is <%=receivedValue%>
</h2>
<h3>
     <%if(receivedValue == 'bingo') {%>
          <p>bingo!</p>
     <%} else {%>
          <p>not bingo..</p>
     <%}%>
</h3>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s