At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

,

A Guide To Create CRUD Operation On Sails.js & Explaining EJS

  • By Aishwarya Damani
  • October 9, 2018
  • 1925 Views

If you ever struggled to learn Sails.js then this blog is going to be the perfect guide for you to get started with Sails. Well, this blog will help you with how to create a basic CRUD Operation On Sails.js (CREATE, READ, UPDATE, DELETE) API which you can use as a foundation for any of your application. Also, we ought to cover all the must known factors of sails in this blog so hope you guys will enjoy reading it. Before jumping into the topic, let me give you a small glimpse of What is sails & why Sails.

Why Sails?

Though there are many nodejs frameworks like Hapi, Express, I chose to write these APIs using sails framework, because Sails is a node web framework whose look and feel is similar to that of rails. It is similar to a “back-end web” framework which helps you do things like build APIs, serve HTML files, and handles thousands of users simultaneously. But, instead of using HTML files Sails uses EJS (Embedded JavaScript)files like how people working in RoR use ERB(Embedded Ruby)files for the front-end purpose. Also it is very simple, easy and enable us to write very minimal amount of code by providing support for routing, authentication, middleware and thereby much flexible than other frameworks.
Before getting started with writing APIs make sure you have installed the latest version of node or at least a node version >= 9.5.0 using the below command,

sudo apt-get install nodejs

 

Topics To Be Covered:

  1. Features of sails
  2. Installation
    • Creating a sails application
    • Creating a user-defined model and controller in a sails application
  1. Database connectivity
  2. Simple CRUD Operation
  3. Testing APIs in postman
  4. Introduction to EJS?
    • What is EJS
    • Basic Tags of EJS
    • How to create views
    • How to code in EJS

 

Features Of Sails

  1. 100% Javascript
  2. Any database
  3. Powerful Associations
  4. Declarative, reusable security policies.

The above mentioned features are verified personally.
100% Javascript
Application in sails are purely written in javascript. If a person is familiar with javascript he/she can understand and build any application in sails very easily.
Any Database
Sails can cope up with any database, let that be MongoDB, PostgreSQL, MySQL, Redis or Local disk.
Powerful Associations
Sails allows us to perform different kinds of associations such as (one-to-many, many-to-many). For instance, you can assign multiple names associated per model and also assign different models to different databases in sails.
Declarative, reusable security policies
The policies created in sails application are reusable. If a person wants to use a set of code in all the controllers throughout the application , he/she can write a policy and use it.

Installing Sails.js

We have already done a complete installation guide for Sails.js in our previous blog so follow the below link and there you can find the installation part, a complete anatomy of the Sails app and also the user defined model and controllers of the sails application explained in detail here. Getting Started With Sails.js

Database Connectivity

We will be using “MongoDb” which is a no-sql database and which goes well with sails applications. To know more about mongodb just click the keyword mentioned “mongodb. Not necessary that the developer must use only MongoDb for storing the data. He/she can use any database as sails has a feature of “Any database” as mentioned earlier.
For database connectivity, open the file config/datastores.js and also open the config/sessions.js file(as we are using sails version 1.0.2 which is the latest version) in any editor, I personally prefer Visual Studio Code as it makes the work even more simpler. To download visual studio code use the following link https://code.visualstudio.com/ . If you use a sails version lesser than 1.0.2 there, you will have a file named as config/connections.js. After opening the file, you will find some commented lines which will have the adapter and url of the database. By default it is “mysql”. To change it to mongodb,
Sails.js
Where“category” is the database name. But, don’t forget to install corresponding NPM for any adapter you configure. Lets install sails-mongo. To install sails-mongo run the command mentioned below

sudo npm install sails-mongo

 

Simple CRUD Operation

 

Function CREATE Category On Sails :

 

/**
* CategoryController
*
* @description :: Server-side actions for handling incoming requests.
* @help :: See https://sailsjs.com/docs/concepts/actions
*/
module.exports = {
 /**
 * `CategoryController.create()`
 */
create: function (req, res) {
 let data;
   // to convert category name's first letter capital
 data = { name: req.body.name.charAt(0).toUpperCase() + req.body.name.slice(1) }
 Category.create(data).fetch().exec(function (err, category) {
   if (err) return (err);
   return res.json(category);
 })
},

 

READ Category On Sails :

 

/**
 * `CategoryController.show()`
 */
 show: function (req, res) {
   Category.find().exec(function (err, category) {
     return res.json(category);
   });
 },

 

UPDATE Category On Sails :

 

/**
 * `CategoryController.edit()`
 */
edit: function (req, res) {
   let query;
   let data;
   query = { "id": req.param('categoryId') }
   // to convert category to first letter capital, rest of them are small letters
   data = { name: req.body.name.charAt(0).toUpperCase() + req.body.name.slice(1) }
   Category.update(query,data).fetch().exec(function (err, category) {
     categoryName = data.name;
     return res.json(category)
   })
 },

 

DELETE Category On Sails :

 

/**
 * `CategoryController.delete()`
 */
 delete: function (req, res) {
   let query;
   query = { "id": req.param('categoryId') }
   Category.destroy(query).fetch().exec(function (err, category) {
     if (err) return(err);
     return res.json(category)
   })
 },
 };

After writing the CRUD operation for the respective controller, the routes are to be defined in the config/routes.js. After everything is done, your application will be ready to run.

Config/routes.js

'/': {
  view: 'pages/homepage'
},
'post /category': 'CategoryController.create',
'get /index': 'CategoryController.show',
'post /category/update/:categoryId': 'CategoryController.edit',
'get /category/delete/:categoryId': 'CategoryController.delete',

 
CRUD Sails
The routes.js file will contain the routes where routes are defined as ‘method /routeName’ : ‘Controller.functionName’. After finishing all the above mentioned tasks, run the application.

Finally the application will runs like as we shown on the above screen,

Testing APIs in Postman

 

Creating A category:

CRUD Sails

Listing The Categories:

CRUD Sails

Updating The Category:

CRUD Sails

List After Updating

 

Sails

Deleting A Category

List After Deletion:


That’s all from the back-end operations, now we will look into the concept called EJS which will give us the clear picture of the front-end user interface.

What Is EJS?

EJS(Embedded JavaScript) is a simple templating language that lets you generate HTML markup with plain JavaScript, which helps in speedy execution, which takes minimal development time, easy to debug, simple syntax, combines with the express view system.

Basic Tags In EJS

We will start with some of the basic tags in ejs so that implementing the logic becomes easier
Tags which are used in the application mentioned here :

  1. <% – This is the ‘Scriptlet’ tag, which is used for control-flow statements and where output is not required.

Example: <% if ( categoryName ) { %>

  1. <%= – This tag outputs the value into the template (HTML escaped),i.e, using this tag, we can display the value which we got from the back-end APIs.

Example: <input name=“name” value=<%= categoryName %>”/>

  1. <%- -This tag outputs the unescaped value into the template.

Example: <td class=<%- className %> vertical-align”>
There are many more tags but we have used only the above 3 in our sample application.

How To Create Views

Earlier, we discussed all about the backend APIs like How to write an API in sails , How to run those APIs in postman. Now, we will discuss about how to access those data in the front-end. Sails is a Node.js MVC framework which is inspired by Ruby on Rails. In sails, the front-end used is ejs(Embedded JavaScript) like how erb(Embedded RuBy) is used in Ruby on Rails. EJS has certains rules on accessing the back-end data. For rendering the page, the line used in the back-end is :

return res.render(‘path to be rendered’, {data});

 
where data are to be given in the form of “key” : value. For multiple values, we have “,” separator which separates one data from another.
Example:
CRUD Sails
And to redirect, the line used is :
CRUD Sails
The front-end HTML should be written in config/views folder where the developer can create multiple folder and files. The above mentioned paths are also written in config/views folder.

How To Code In EJS

Coding in ejs is very simple if the syntax is known. If the developer is well versed with HTML and EJS syntax programming becomes fun. So, let’s code. Below are snippets of code which will demonstrate and give you an idea about how to code in ejs.

<html>
<head>
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
 <center><h2 class="categories-index">All Categories</h2></center>
 <a href="/category">
   <button title="create category" type="button" class="btn btn-sm pull-right" style="margin-right: 5px;">
     <i class="fa fa-lg fa-plus-circle"></i>
   </button>
 </a>
 <% if ( category == '' ) { %>
   <h2>No category</h2>
 <% } else { %>
   <div>
     <div class="container">
       <div class="col-md-12">
         <table id="example" class="table bgborder col-md-10">
           <thead class="verticalAlign">
             <tr class="even">
               <th>Index</th>
               <th>Category Name</th>
               <th>Edit / Delete</th>
             </tr>
           </thead>
           <tbody>
             <% category.forEach( function( category, index ) { %>
               <% className = (index + 1)%2 == 0 ? 'even' : 'odd' %>
                 <tr>
                   <td class="<%- className %> vertical-align">
                     <%= index + 1 %>
                   </td>
                   <td class="<%- className %> vertical-align">
                     <a href='/category/sort/<%= category.id %>'><%= category.name %></a>
                   </td>
                   <td class="<%- className %> vertical-align">
                     <a href='/category/update/<%= category.id %>'>
                       <button title="update category" type="button" class="btn btn-sm" style="margin-right: 5px; margin-bottom: 5px; ">
                         <i class="fa fa-lg fa-edit"></i>
                       </button>
                     </a>
                     <% assetExist = asset.includes(category.id) %>
                     <% if ( assetExist ) { %>
                       <button disabled title="delete category" type="button" class="btn btn-sm" style="margin-right: 5px; margin-bottom: 5px;">
                         <i class="fa fa-lg fa-trash"></i>
                       </button>
                     <% } else { %>
                       <a href='/category/delete/<%= category.id %>'>
                         <button title="delete category" type="button" class="btn btn-sm" style="margin-right: 5px;">
                           <i class="fa fa-lg fa-trash"></i>
                         </button>
                       </a>
                     <% } %>
                   </td>
                 </tr>
             <% }); %>
           </tbody>
         </table>
         <div class="col-md-1"></div>
       </div>
     </div>
   </div>
 <% } %>
</body>
</html>

That’s it guys, hope you will find it helpful and soon i’ll pick another interesting topic and feed you guys with more informative blog. Also you can read more technical blogs on our largest blog repository which would be perfect place to learn about all the latest technologies pinned with intellectual topics, parallely don’t forget to share us your thoughts and queries on the comment box. We’re glad to help you out.

Aishwarya Damani

An aspiring adolescent started her career as Software Engineer Trainee and slowly she's mastering all the rising technologies like Nodejs, Express.js, React.js, MongoDB, Sails. On the other hand, a perfect decision maker who is passionate about coding. Wait! there's half a lie! Yeah, this crazy foodie has an intense long lasting affair on trying different foods & exploring places.