Why Sails.js Is One Of My Favourite Node.js Web Framework?

Why Sails.js Is One Of My Favourite Node.js Web Framework?

Node.js is a great platform for rapid application development using the same language (JavaScript) on the server that is used on the client, as well as using the JSON format to exchange data. One issue I have run into with Node is it can be cumbersome when building full-featured web applications. This is where Sails.js enters the picture.

Sails is a Javascript framework designed to resemble the MVC architecture from frameworks like Ruby on Rails. It makes the process of building Node.js apps easier, especially APIs, single page apps and realtime features, like chat.

I am using Sails.js for more then one year and honestly I fell in love with it , in one word it's simplest , coolest and one of best web framework for web application development. 

Installation

To install Sails, it is quite simple. The prerequisites are to have Node.js installed and also npm, which comes with Node. Then one must issue the following command in the terminal:

Create a New Project

In order to create a new Sails project, the following command is used:


Sails will generate a new folder named and add all the necessary files to have a basic application built. To see what was generated, just get into the folder and run the Sails server by issuing the following command in the terminal:




Folder Structure:Sails's default port is 1337, so if you visit you should get the Sails default page.

The Folder

The folder contains subdirectories for the Javascript and CSS files that should be loaded during runtime. This is the best place to store auxiliary libraries used by your application.

The Folder

Contains the files that are publicly available, such as pictures your site uses, the favicon, etc.

The Folder

This is one of the important folders. Sails is designed to be flexible. It assumes some standard conventions, but it also allows the developer to change the way Sails configures the created app to fit the project's needs. The following is a list of configuration files present in the folder:

  • - used to configure the database adapters
  • - general settings for the application
  • - asset settings for CSS and JS
  • - code that will be ran before the app launches
  • - folder containing translations
  • - user rights management configuration
  • - the routes for the system
  • - view related settings

The documentation contains detailed information on each of these folders.

The Folder

The application's views are stored in this folder. Looking at its contents, we notice that the views are generated by default as EJS (embedded JavaScript). Also, the folder contains views for error handling (404 and 500) and also the layout file () and the views for the home controller, which were generated by Sails.

The Folder

This folder is composed from a buch of sub-folders:

  • the folder contains the adapters used by the application to
  • handle database connections
  • the folder contains the application controllers
  • the application's models are stored in the folder
  • in the folder are stored rules for application user access
  • the api services implemented by the app are stored in the
  • folder

Configure the Application

So far we have created our application and took a look at what was generated by default, now it's time to configure the application to make it fit our needs.

General Settings

General settings are stored in the file. The configurable options for the application are:

  • application name ()
  • the port on which the app will listen ()
  • the application environment; can be either development or production ()
  • the level for the logger, usable to control the size of the log file ()

Note that by setting the app to production, makes Sails bundle and minify the CSS and JS, which can make it harder to debug.

Routes

Application routes are defined in the file. As you'd expect, this file will be the one that you will most often work with as you add new controllers to the application.

The routes are exported as follows, in the configuration file:

Views

Regarding views, the configurable options are the template engine to be used and if a layout should or not be used, for views.

Models

Models are a representation of the application data stored in a database. Models are defined by using attributes and associations. For instance, the definition of a model might look like this:

Sails uses Waterline as its ORM, and it provides a lot of power for developing rapidly. The field dictates where the data will be stored, and you can mix and match, so you can have some models stored in MySQL and others in Redis, for instance. I think this is a really cool feature. You can set validation, etc. on them. You can write custom methods on your models to extract “higher-order” data from them. Best of all, just having a model gets you a ton of routes (CRUD blueprints and REST endpionts) out of the box (and they all work with Websockets!):

# Backbone ConventionsGET:/:controller => findAll() GET : /:controller/read/:id=> find(id)POST:/:controller/create=> create()POST:/:controller/create/:id=> create(id)PUT:/:controller/update/:id=> update(id)DELETE:/:controller/destroy/:id=> destroy(id)# You can also explicitly state the actionGET:/:controller/find=> findAll()GET:/:controller/find/:id=> find(id)POST:/:controller/create=> create(id)PUT:/:controller/update/:id=> update(id)DELETE:/:controller/destroy/:id=> destroy(id)

The communication with the underlying database is done through adapters. Adapters are defined in and are configured in the file. At the moment of writing this article, Sails comes with three adapters: memory, disk and mysql but you can write your own adapter (see the documentation for details).

Once you have a model defined you can operate on it by creating records, finding records, updating and destroying records.

Controllers

Controllers are placed in . A controller is created using the following command:

This command will generate a object. Actions are defined inside this object. Actions can also be generated when you issue the command:

Actions receive as parameters the request and the response objects, which can be used for getting parameters of the URI (the request object) or output in the view (using the response object).

To communicate with the model, the callback of the appopriate action is used. For instance, in the case of querying a database with , the following pattern is used to manipulate the model:

Views

Views are used to handle the UI of the application. By default, views are handled using EJS, but any other templating library can be used. How to configure views was discussed previously in the Configuration chapter.

Views are defined in the directory and the templates are defined in the folder.

There are mainly four types of views:

  • server-side views
  • view partials
  • layout views
  • client-side views

Server-Side Views

Their job is to display data when a view is requested by the client. Usually the method corresponds to a client with the appropriate view. But if no controller or action exists for a request, Sails will serve the view in the following fashion: .

The Layout View

The Layout can be found in . It is used to load the application assets such as stylesheets or JavaScript libraries.

Have a look at the specified file:

<!DOCTYPE html>

<html>

 <head>

   <title><%- title %></title>

 

   <!-- Viewport mobile tag for sensible mobile support -->

   <meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, maximum-scale=1&quot;>

 

   <!-- JavaScript and stylesheets from your public folder are included here -->

   <%- assets.css() %>

   <%- assets.js() %>

 </head>

 

 <body>

   <%- body %>

 

   <!-- Templates from your view path are included here -->

   <%- assets.templateLibrary() %>

 </body>

</html>

The lines and load the CSS and JS assets of our application and the loads the client templates.

Client-Side Templates

These are defined in the and are loaded as we saw above.

Routes

We discussed how to configure routes in the Configuration chapter.

There are several conventions that Sails follows when routes are handled:

  • if the URL is not specified in the the default route for a URL is with the obvious meanings for controller and action and being the request parameter derived from the URL.
  • if is not specified, Sails will redirect to the appropriate action. Out of the box, the same RESTful route conventions are used as in Backbone.
  • if the requested controller/action do not exist, Sails will behave as so:
  • if a view exists, Sails will render that view
  • if a view does not exist, but a model exists, Sails will return the JSON form of that model
  • if none of the above exist, Sails will respond with a 404

 

 

Sails.js Features:

Sails is a lightweight framework that sits on top of Express. Its ensemble of small modules work together to provide simplicity, maintainability, and structural conventions to Node.js apps. Below are the features of it:

100% JavaScript

Like other MVC frameworks, Sails is built with an emphasis on developer happiness and a convention-over-configuration philosophy. But Node.js takes this principle to the next level. Building on top of Sails means your app is written entirely in JavaScript, the language you and your team are already using in the browser. Since you spend less time context-shifting, you're able to write code in a more consistent style, which makes development more productive and fun.

Any database

Sails bundles a powerful ORM, Waterline, which provides a simple data access layer that just works, no matter what database you're using. In addition to a plethora of community projects, officially supported adapters exist for MySQL, MongoDB, PostgreSQL, Redis, and local disk.

Powerful associations

Sails offers a new take on the familiar relational model, aimed at making data modeling more practical. You can do all the same things you might be used to (one-to-many, many-to-many), but you can also assign multiple named associations per-model (for instance, a cake might have two collections of people: "havers" and "eaters"). Better yet, you can assign different models to different databases, and your associations/joins will still work-- even across NoSQL and relational boundries. Sails has no problem implicitly/automatically joining a MySQL table with a Mongo collection and vice versa.

Auto-generate REST APIs

Sails comes with blueprints that help jumpstart your app's backend without writing any code. Just run and you'll get an API that lets you search, paginate, sort, filter, create, destroy, update, and associate dentists. Since these blueprint actions are built on the same underlying technology as Sails, they also work with Websockets and any supported database out of the box.

Support WebSockets with no additional code

In the past, adding realtime/"comet" features meant maintaining two separate code bases. But since the request interpreter in Sails translates incoming socket messages for you, they're automatically compatible with every route in your Sails app, as well as any existing Express routes/middleware. Normalization of parameters, the session, and the streaming interface are all taken care of. In other words, the code you write works with WebSockets and HTTP, without doing any extra work.

Declarative, reusable security policies

Sails provides basic security and role-based access control by default in the form of policies - simple, reusable middleware functions that run before your controllers and actions. Writing policies encourages encapsulation, which dramatically simplifies your business logic and reduces the total amount of code you need to write. Policies are interchangeable with Express/Connect middleware, which means you can plug in popular npm modules like Passport. Finally, like most things in Sails, your policies work for both WebSockets and HTTP automatically.

Front-end agnostic

While the promise of "one language/framework to rule them all" is certainly enticing, it isn't always realistic. Sails is compatible with any front-end strategy; whether it's Angular, Backbone, iOS/ObjC, Android/Java, Windows Phone, or something else that hasn't been invented yet. Plus it's easy to serve up the same API to be consumed by another web service or community of developers.

Flexible asset pipeline

If you are building an app for the browser, you're in luck. Sails ships with Grunt- which means your entire front-end asset workflow is completely customizable, and comes with support for all of the great Grunt modules which are already out there. That includes support for LESS, SASS, Stylus, CoffeeScript, JST, Jade, Handlebars, Dust, and many more. When you're ready to go into production, your assets are minified and gzipped automatically. You can even compile your static assets and push them out to a CDN like CloudFront to make your app load even faster.

Rock-solid foundation

Sails is built on Node.js, a popular, lightweight server-side technology that allows developers to write blazing fast, scalable network appliations in JavaScript. Sails uses Express for handling HTTP requests, and wraps socket.io for managing WebSockets. So if your app ever needs to get really low-level, you can access the raw Express or socket.io objects. Another nice side-effect is that your existing Express routes work perfectly well in a Sails app, so migrating an existing Node app is a breeze.

Why I have I Prefer Sails.js:

A tantalizing choice

Before Sails.js, I dissected and studied Derby, Meteor, small Rendr, unpretentious Geddy and even the exotic Tower. I had to work with all these things for several days, and I thought that Derby was the coolest. I nearly made up my mind to select it for the project, but the lack of proper documentation and the need to work with the code carefully to correct a simple error forced me to continue my search.

As soon as I had said goodbye to MEAN.IO, I came across Sails.js, very young, but with an impressive number of stars on GitHub. Then the project was in its infancy, but I really liked the desire of the developers to comply with the ideology of the great and terrible RoR, so I decided to learn more about it. I have to mention that Sails.js changed quite a lot, but the developers always give enough time to writing the documentation, so shifting to the next version never causes any problems.

Cool features of Sails.js

The first thing I wanted to note is that Sails.js is primarily an MVC-framework. If you are familiar with any other popular frameworks (RoR, Yii, CodeIgniter, ASP .NET MVC), you will feel comfortable immediately after you get acquainted with the structure of the Sails.js project, because you will see all the folders familiar from MVC pattern: models, views, controllers and other things typical for such products.

As for the killer features, there are really a lot of them here. For instance, full integration with socket.io. This means that developers using Sails.js can easily develop applications in real-time mode! They will not have to struggle with the integration or adjusting the work of the program with Node.js, as everything works quite correctly just out of the box.

Special emphasis has to be made on console utilities, which provide total automation for routine operations. You would like to create a new controller, wouldn’t you? No problem! Write a single command, and the draft for your controller is ready. What did you say? Along with the controller, you also need a model? Again, no problem, there is also a command for that. A little later we will see how it all works.

Something I particularly liked when I worked with Sails.js was its friendliness to other frameworks/libraries. This framework does not try to solve all possible problems on its own and delegates non-core tasks to auxiliary solutions. Thus, the problem of making Sails.js friendly to your favorite client framework becomes a no-brainer.

Sails.js is supplied together with quite a powerful ORM called Waterline. It is fast, easy to use and friendly to any database. Immediately out of the box, we are offered adapters for the most popular DBMS solutions: MySQL, PostgreSQL, Redis, and MongoDB give the possibility to use a usual file for data storage. Such a storage space is convenient to use in the development phase, and today we will see it on an example from practice.

I will show the most special feature of Sails.js at the very end. Just imagine: RESTful API Sails.js automates all the routine associated with the generation very well. In practice, this means that the framework can automatically create API for common operations (CRUD, pagination, search) with the model you created, with the routes set. To create a model here is that simple, and you can work with it immediately, without writing a single line of code. To tell you a secret, it is this feature that inspired me to get better acquaintance with Sails.js.

I can go on about the goodies of Sails.js for a long time, but I would not want to take the bread from the authors of [official website] (sailsjs.org). Therefore, for more information, I recommend that you visit their website, and in this article we’d better examine the potential by a case study.

Prepare the environment

To reach this goal, we need a number of tools. These are, first of all, Node.js, NPM and Sails.js. It is best to deal with these components in their native environment, that is, unix-like operating systems (Linux, OS X, BSD). In Windows, it is theoretically possible to set up this bundle, but I have personally discovered some weird errors lately.

If you do not have an installed Linux distribution set, then do not waste your time with virtuals and immediately use DigitalOcean, a cloud hosting service. The DO presets include a draft with the latest version of Ubuntu and customized Node.js, so preparing the entire necessary work environment is only a matter of a few clicks for you. This is the option I chose to use.

That is to say, make up your mind, get ready and set Sails.js with the help of the command sudo npm-g install sails.

I strongly suggest if you are looking for best node.js web framework for building great web application go for sails.js framework. Sails.js was easy to get up and running, and there were plenty of online resources to cover key features. Creating views and controllers were straightforward, but working with a database backend presented a steeper learning curve. Sails.js has a great community including an active Google Group, an IRC Channel (#sailsjs), and plenty of online resoures, so there is plenty of help when you have questions.

Thanks for reading!

Love the post? Hate the post? Have other Tips? Please Leave a comment below!

About the Author

Sandip Das is a tech start-up adviser as well as has serving multiple international  IT firms , tech-entrepreneurs as Individual IT consultant / Sr. Web Application developer / JavaScript Architect , worked as a team member, helped in development and in making IT decision .His desire is to help both the tech-entrepreneurs & team to help build awesome web based products , make team more knowledgeable , add new Ideas to give WOW expression in product.

More on Sandip here at LinkedIn

Shivam Kumraa

Full stack developer(MERN, Node js, React Js, Vue Js, Python, Django)

2 年

Sails is the most horrible framework

回复
Toupali Chakraborty

Online Bidder/Lead generation/Business Development/IT Sales

8 年

I really like all your post sandy

要查看或添加评论,请登录

社区洞察

其他会员也浏览了