Sails.js (GitHub) is a convention-over-configuration type of a framework. This means that it’s similar in philosophy to Ruby on Rails. Sails.js is a true MVC framework, unlike Express.js which relies on developers for adding ORMs like Mongoose. Sails.js uses the Waterline ORM.
To get started with Sails.js:
$ npm -g install sails@0.10.5
This will give you the sails command, and you can see the list of available options with:
$ npm sails -h
Let’s use the new
command to generate an app (.../sails
):
$ sails new sails
After the app has been generated, start it with lift
:
$ cd sails
$ sails lift
Now, if you go to the http://localhost:1337, you will see a Sails.js page with some instructions and links (Figure 1).
To generate resources, you can use these commands:
$ sails generate api NAME
: Building a new model and controllerapi/models/NAME.js and api/controllers/NAMEController.js
$ sails generate model NAME [attribute1:type1, attribute2:type2 ... ]
: Building a new modelapi/models/NAME.js
with attributes (optional).$ sails generate controller NAME [action1, action2, ...]
: Building a new controllerapi/controllers/NAMEController.js
with actions (optional).$ sails generate adapter NAME
: Building a new adapterapi/adapters/NAME
.$ sails generate generator NAME
: Building a new generator.
Each controller is structured as a module with methods. These methods are actions, e.g., /controller/action
. Each action has a request and response. Their arguments are inherited from their Express.js counterparts. To illustrate this point, let’s create a controller and add some custom code to it using Express.js methods —response.json()
and response.redirect()
.
Firstly, run this command:
$ sails generate api user
Open newly created file .../sails/api/controllers/UserController.js
. In it, add two actions “json” that will output the current time, and “buy-oauth” that will utilize the redirect:
module.exports = {
json: function (request, response) {
response.json({time: new Date()})
},
'buy-oauth': function (request, response) {
return res.redirect('https://gum.co/oauthnode');
}
};
If you go to the http://localhost:1337/user/json, you’ll see:
{ "time": "2014-09-09T14:59:28.377Z" }
And if you go to the http://localhost:1337/user/buy-oauth
, you’ll be redirected to the Introduction to OAuth with Node.js [webapplog.com, 2014] page.
So the conclusion here is that it will be easy for someone who’s already familiar with Express.js to write controllers in Sails.js. Controllers are intermediaries between views and models, and typically contain the bulk of the code and logic! For more information on Sails.js concepts and its documentation go to http://sailsjs.org/#/documentation/concepts and http://irlnathan.github.io/sailscasts.
PS: This text is from my new book Pro Express.js.
4 thoughts on “Sails.js 101”