Learn Sails.js with Examples: How to Use MVC, ORM, REST, and Sockets
- Benefits of using Sails.js for web development - How to install Sails.js and create a new project H2: How to use Sails.js in action - How to create models, controllers, views, and routes with Sails.js - How to use blueprints, policies, hooks, and services with Sails.js - How to use sockets, pub/sub, and realtime communication with Sails.js H3: How to test and deploy Sails.js applications - How to write unit tests and integration tests with Sails.js - How to use sails lift, sails console, and sails debug commands - How to deploy Sails.js applications to Heroku, AWS, or other platforms H4: How to learn more about Sails.js - How to access the official documentation and tutorials of Sails.js - How to join the community and get support from other developers - How to find and contribute to open source projects using Sails.js Table 2: Article with HTML formatting What is Sails.js and why should you use it?
If you are looking for a Node.js framework that can help you build scalable, data-driven, and realtime web applications, you might want to check out Sails.js. Sails.js is a MVC (model-view-controller) framework that follows the "convention over configuration" principle. It's inspired by the popular Ruby on Rails web framework, but with support for the requirements of modern apps: data-driven APIs with a scalable, service-oriented architecture.
sails.js in action pdf 37
In this article, we will explore what Sails.js can do for you, how to install it and create a new project, and how to use it in action. We will also show you how to test and deploy your Sails.js applications, and how to learn more about this amazing framework.
How to use Sails.js in action
Sails.js provides a powerful set of tools and features that make web development easier and faster. Let's take a look at some of them.
How to create models, controllers, views, and routes with Sails.js
Models are the core of any web application. They represent the data and logic of your app. With Sails.js, you can create models using the built-in ORM (object-relational mapping) tool called Waterline. Waterline allows you to define your models using a simple JSON syntax, and it automatically creates the database tables and schema for you. You can also use any database you want with Waterline, as it supports SQL, NoSQL, and even custom adapters.
To create a model with Sails.js, you can use the sails generate command in your terminal. For example, if you want to create a model called User with attributes name, email, and password, you can type:
sails generate model User --attributes name:string,email:string,password:string
This will create a file called User.js in your api/models folder. You can edit this file to add validations, associations, or custom methods to your model.
Controllers are the components that handle the requests from your clients. They contain the actions that perform some logic on your models or other services. With Sails.js, you can create controllers using the sails generate command as well. For example, if you want to create a controller called UserController with actions create, find, update, and destroy, you can type:
sails generate controller UserController --actions create find update destroy
This will create a file called UserController.js in your api/controllers folder. You can edit this file to add your business logic to each action.
Views are the templates that render the HTML output for your clients. With Sails.js, you can use any templating engine you want, such as EJS, Handlebars, Jade, or React. By default, Sails.js uses EJS, which is a simple and powerful templating engine that lets you embed JavaScript code in your HTML. To create a view with Sails.js, you can simply create a file with the .ejs extension in your views folder. For example, if you want to create a view called index.ejs that displays a list of users, you can type:
Sails.js in action
List of users
-
Routes are the mappings between the URLs and the controllers. With Sails.js, you can define your routes using a simple JSON syntax in your config/routes.js file. For example, if you want to map the URL /users to the find action of the UserController, you can type:
module.exports.routes = 'GET /users': 'UserController.find' ;
Sails.js also provides a feature called blueprints, which automatically generates RESTful routes for your models and controllers. This means that you don't have to write any code to create basic CRUD (create, read, update, delete) operations for your app. You can enable or disable blueprints in your config/blueprints.js file.
How to use blueprints, policies, hooks, and services with Sails.js
Blueprints are the default CRUD actions that Sails.js provides for your models and controllers. They allow you to quickly prototype your app without writing any code. For example, if you have a model called User, Sails.js will automatically create the following routes for you:
GET /user -> UserController.find GET /user/:id -> UserController.findOne POST /user -> UserController.create PUT /user/:id -> UserController.update DELETE /user/:id -> UserController.destroy
You can customize the behavior of blueprints by editing the config/blueprints.js file. For example, you can change the prefix of the routes, the default limit of records, or the actions that are enabled or disabled.
Policies are the middleware functions that control the access to your controllers and actions. They allow you to implement authentication, authorization, or any other logic that you want to run before or after your controllers. With Sails.js, you can create policies using the sails generate command as well. For example, if you want to create a policy called isLoggedIn that checks if the user is logged in, you can type:
sails generate policy isLoggedIn
This will create a file called isLoggedIn.js in your api/policies folder. You can edit this file to add your logic to the policy. For example:
module.exports = function(req, res, next) // Check if the user is logged in if (req.session.user) // If so, proceed to the next middleware function return next(); // If not, redirect to the login page return res.redirect('/login'); ;
To apply a policy to a controller or an action, you can edit the config/policies.js file. For example, if you want to apply the isLoggedIn policy to all actions of the UserController except the create action, you can type:
module.exports.policies = UserController: '*': 'isLoggedIn', 'create': true ;
Hooks are the functions that run before or after certain events in your app. They allow you to add custom functionality or integrate with external services. With Sails.js, you can create hooks using the sails generate command as well. For example, if you want to create a hook called sendEmail that sends an email when a new user is created, you can type:
sails generate hook sendEmail
This will create a folder called sendEmail in your api/hooks folder. You can edit the index.js file in this folder to add your logic to the hook. For example:
module.exports = function(sails) return // Run when sails loads-- be sure and call `next()`. initialize: function(next) // Subscribe to the User model's "afterCreate" event sails.on('hook:orm:loaded', function() User.afterCreate(function(user) // Send an email using some external service EmailService.sendWelcomeEmail(user); ); ); // Call next() when finished return next(); ; ;
logic that you want to use in your app. With Sails.js, you can create services using the sails generate command as well. For example, if you want to create a service called EmailService that handles sending emails, you can type:
sails generate service EmailService
This will create a file called EmailService.js in your api/services folder. You can edit this file to add your logic to the service. For example:
module.exports = // Send a welcome email to a new user sendWelcomeEmail: function(user) // Use some external email provider EmailProvider.send( to: user.email, subject: 'Welcome to Sails.js', text: 'Hello ' + user.name + ',\n\nThank you for joining Sails.js. We hope you enjoy building awesome web apps with us.\n\nCheers,\nThe Sails.js Team' ); ;
To use a service in your controllers or other services, you can simply require it and call its methods. For example:
var EmailService = require('../services/EmailService'); module.exports = // Create a new user and send a welcome email create: function(req, res) // Get the user data from the request var userData = req.body; // Create a new user in the database User.create(userData).exec(function(err, user) if (err) // Handle error return res.serverError(err); // Send a welcome email to the user EmailService.sendWelcomeEmail(user); // Return the user as a response return res.ok(user); ); ;
How to use sockets, pub/sub, and realtime communication with Sails.js
Sockets are the technology that enables realtime communication between your server and your clients. They allow you to send and receive messages in both directions, without refreshing the page or polling the server. With Sails.js, you can use sockets with ease, as it integrates with Socket.io, the most popular socket library for Node.js.
To use sockets with Sails.js, you need to do two things: connect your clients to your server using sockets, and subscribe your clients to some events or models using pub/sub.
To connect your clients to your server using sockets, you need to include the sails.io.js file in your HTML page. This file is automatically generated by Sails.js and exposes a global variable called io. You can use this variable to create a socket connection with your server. For example:
// Create a socket connection with the server var socket = io.connect(); // Listen for some events from the server socket.on('connect', function() console.log('Connected to the server'); ); socket.on('disconnect', function() console.log('Disconnected from the server'); ); socket.on('message', function(data) console.log('Received a message from the server:', data); );
To subscribe your clients to some events or models using pub/sub, you need to use the socket methods provided by Sails.js. These methods allow you to subscribe or unsubscribe to any event or model that is published by your server. For example:
// Subscribe to the User model events socket.get('/user', function(data) console.log('Subscribed to User model:', data); ); // Subscribe to a specific user instance events socket.get('/user/1', function(data) console.log('Subscribed to User instance:', data); ); // Unsubscribe from the User model events socket.delete('/user', function(data) console.log('Unsubscribed from User model:', data); );
To publish events or models from your server to your clients using pub/sub, you need to use the model methods provided by Sails.js. These methods allow you to publish any event or model that is subscribed by your clients. For example:
module.exports = // Create a new user and publish it to all subscribers create: function(req, res) // Get the user data from the request var userData = req.body; // Create a new user in the database User.create(userData).exec(function(err, user) if (err) // Handle error return res.serverError(err); // Publish the user creation event to all subscribers User.publishCreate(user); // Return the user as a response return res.ok(user); ); , // Update a user and publish it to all subscribers update: function(req, res) // Get the user id and data from the request var userId = req.params.id; var userData = req.body; // Update the user in the database User.update(userId, userData).exec(function(err, users) if (err) // Handle error return res.serverError(err); // Get the updated user var user = users[0]; // Publish the user update event to all subscribers User.publishUpdate(user.id, user); // Return the user as a response return res.ok(user); ); , // Destroy a user and publish it to all subscribers destroy: function(req, res) // Get the user id from the request var userId = req.params.id; // Destroy the user in the database User.destroy(userId).exec(function(err, users) if (err) // Handle error return res.serverError(err); // Get the destroyed user var user = users[0]; // Publish the user destroy event to all subscribers User.publishDestroy(user.id, user); // Return the user as a response return res.ok(user); ); ;
How to test and deploy Sails.js applications
Testing and deploying your Sails.js applications is easy and fun. Let's see how.
How to write unit tests and integration tests with Sails.js
Unit tests are the tests that verify the functionality of a single unit of code, such as a function, a class, or a module. Integration tests are the tests that verify the functionality of multiple units of code working together, such as a controller, a model, or a service.
With Sails.js, you can write unit tests and integration tests using any testing framework you want, such as Mocha, Jasmine, or Jest. You can also use any assertion library you want, such as Chai, Expect, or Should. You can also use any mocking library you want, such as Sinon, Nock, or Mockery.
To write unit tests and integration tests with Sails.js, you need to do three things: install your testing framework and libraries, create your test files and folders, and run your tests.
To install your testing framework and libraries, you can use npm or yarn in your terminal. For example, if you want to use Mocha and Chai for testing, you can type:
npm install --save-dev mocha chai
To create your test files and folders, you can follow any convention you want, but a common one is to create a test folder in your root directory, and then create subfolders for each type of test. For example:
test/ unit/ models/ User.test.js services/ EmailService.test.js integration/ controllers/ UserController.test.js
To run your tests, you can use any tool you want, such as npm scripts, gulp tasks, or grunt tasks. For example, if you want to use npm scripts to run your tests with Mocha, you can edit your package.json file and add the following scripts:
"scripts": "test": "mocha test//*.test.js", "test:unit": "mocha test/unit//*.test.js", "test:integration": "mocha test/integration//*.test.js"
Then, you can run your tests in your terminal by typing:
npm test
How to use sails lift, sails console, and sails debug commands
Sails.js provides some useful commands that help you run and debug your app. Let's take a look at some of them.
sails lift is the command that starts your app in development mode. It loads your app configuration, models, controllers, services, hooks, policies, routes, views, and assets. It also watches for any changes in your files and reloads them automatically. To use sails lift, you can simply type:
sails lift
This will start your app on port 1337 by default. You can change the port by passing an argument to the command. For example:
This will start your app on port 3000 instead. You can also pass other options to the command, such as --verbose, --silly, or --prod. You can see the full list of options by typing:
sails lift --help
sails console is the command that starts your app in interactive mode. It allows you to access your app's models, controllers, services, hooks, policies, routes, views, and assets from a REPL (read-eval-print loop) interface. You can use sails console to test your app logic, run queries, or perform any other tasks. To use sails console, you can simply type:
sails console
This will start your app and open a REPL interface in your terminal. You can type any JavaScript code in the REPL and see the result. For example:
sails> User.count().exec(console.log) null 3 sails> User.findOne(name: 'Alice').exec(console.log) null name: 'Alice', email: 'alice@example.com', password: '123456', createdAt: 2022-01-14T10:11:12.345Z, updatedAt: 2022-01-14T10:11:12.345Z, id: 1
sails debug is the command that starts your app in debug mode. It allows you to use a debugger tool, such as Chrome DevTools or Visual Studio Code, to inspect and modify your app's code at runtime. You can use sails debug to set breakpoints, watch variables, evaluate expressions, or perform any other debugging tasks. To use sails debug, you need to have Node.js version 8 or higher installed. Then, you can simply type:
sails debug
This will start your app and print a URL in your terminal. You can copy and paste this URL in your browser or debugger tool to open the debugging interface. For example:
Debugger listening on ws://127.0.0.1:9229/12345678-1234-1234-1234-123456789abc For help see https://nodejs.org/en/docs/inspector To start debugging, open the following URL in Chrome: chrome-devtools://devtools/bundled/js_app.html?experiments=true&v8only=true&ws=127.0.0.1:9229/12345678-1234-1234-1234-123456789abc
How to deploy Sails.js applications to Heroku, AWS, or other platforms
Deploying your Sails.js applications to production is easy and fun as well. You can use any platform or service that supports Node.js applications, such as Heroku, AWS, Azure, DigitalOcean, or Google Cloud Platform.
To deploy your Sails.js applications to Heroku, you need to do three things: create a Heroku account and install the Heroku CLI tool, create a Procfile and a .env file for your app configuration, and push your app code to Heroku.
To create a Heroku account and install the Heroku CLI tool, you can follow the instructions on the Heroku website.
To create a Procfile and a .env file for your app configuration, you need to create two files in your root directory. The Procfile is a file that tells Heroku how to run your app. The .env file is a file that stores your app environment variables.
The Procfile should contain one line that specifies the command to start your app. For example:
web: node app.js
The .env file should contain one line for each environment variable that you want to set for your app. For example:
PORT=3000 NODE_ENV=production DATABASE_URL=postgres://user:pass@host:port/dbname
To push your app code to Heroku, you need to use the git commands provided by the Heroku CLI tool. For example:
heroku login heroku create git push heroku master
This will create a new app on Heroku and deploy your code to it. You can see the URL of your app by