Welcome folks today in this blog post we will be building a sails.js backend crud rest api in mysql & mongodb database using javascript. All the full source code and step by step instructions will be shown below.
What is Sails.js??
Sails.js is a MVC Framework based on Ruby on Rails. It is used to developed realtime full stack apps which involve authentication and billing systems also. It’s a great alternative to express.js. It is written purely in Javascript.
Installation
Now we will see how to install the sails.js library globally inside the system. You need to execute the below command to install the sails.js cli inside your system
npm i -g sails
Now after executing the above command you can use the sails command in any folder or directory to create a new sails app.
Creating a Sails App
Now it’s time to create a brand new sails app from scratch. So first of all you need to execute the below commands to create a sails app and also run it inside the browser
sails new <project-name>
Here in the above command you need to replace your project name
sails new crudapp
Here we have the crudapp which is created and now we need to move to this folder. Here in the above screenshot you have two choices either you can choose a fully fledged app containing authentication and secondly you can choose an empty App. I will recommend to choose empty app option 2 as a beginner
cd crudapp
Directory Structure of Sails.js App
Now we will look at all the folder and files structure of a sample sails.js app as shown below
Making the API For the Model in Sails.js
In order to create a api for the model inside sails.js. We need to execute the below command
sails generate api book
This above command will create a BookController.js and a model file called as Book.js as shown below
Running the Sails App
sail lift
When you run the sails.js app for the very first time using the above command you will be presented with two options as shown below
As you are at the development stage I will choose the first option which is for DEV it will create or insert all the data inside the table for you. You don’t need to do anything after passing this option.
Now your app will be started at port number 1337
If you open http://localhost:1337/book you will see the below output
Now as you can see I have previously inserted one record using the post request so that’s why it is showing one record present when we make a get request to the book model. It is returning this json response. This json contains an array of books each having two properties name and the price and also three additional fields which gets created when you create a new record which is the actual id and createdAt and updatedAt.
Creating a new Book in Browser
You can even create a new Book Record inside the browser itself by writing the below url. In this url we will be using the /Create
route and then we will be providing the title and the price of the book as query parameters as shown below
http://localhost:1337/book/Create?name=computer&price=200
As you can see after executing the url inside the browser it is returning the newly created book with the information about the book created.
Testing All Routes of API Using Postman
You can also use postman rest client software for testing routes of API. In postman you select the Method that you need to perform and then write the query parameter inside the form data as shown below. Here we are creating a new record
Fetching All Books Using Get Request
Deleting a Book Using Delete Request Using the ID
As you can see we are deleting a specific book by using it’s id. We are providing the id using the body header i.e. formdata passing it there as shown above.
Updating a Book Using Put Request Using the ID
Now we will be using the put request inside postman to update a specific book information by passing it’s id in the request as shown below
Sails.js ShortCut Routes (Only For Testing)
Sail.js by default also provide some useful shortcut routes for testing only. They are not valid in production mode. These routes are as follows. All these routes for used for crud operations. All these requests are GET requests which can be directly executed in browser
GET http://localhost:1337/book/find/1 -> To get info of a particular book having the id equal to 1
GET http://localhost:1337/book/find -> To get list of all books
GET http://localhost:1337/book/create?name=Learn Java&price=$20 –> To create a new Book Record
GET http://localhost:1337/book/1?name=Learn Java&price=$20 –> To update a specific Book Record having id 1
GET http://localhost:1337/book/destroy/1 -> To delete a specific book having the id 1
Connecting With MySQL in Sails.js
Now we will look how to connect Sails.js with external database such as MySQL. You can download mysql database by installing XAMMP or WAMP which includes MySQL Database with phpmyadmin interface.
As you can see in xampp we started the Apache server and then we started mysql database at port number 3306 as shown above.
So now you need to install the mysql adapter library as shown below to connect with mysql
npm i sails-mysql
And now you need to go to phpmyadmin gui area and there you need to create a new database called db_books as shown below
And now inside the datastores.js file we need to copy paste the below code to connect to the mysql database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
module.exports.datastores = { default: { adapter: 'sails-mysql', user: 'root', password: '', port: '3306', host: '127.0.0.1', database: 'db_books' }, }; |
As you can see we are providing the adapter, username and password and also the port number, hostname also and the database name.
And now we need to copy paste the schema inside the models folder we have a file called Book.js as shown below
api/models/Book.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
/** * Book.js * * @description :: A model definition represents a database table/collection. * @docs :: https://sailsjs.com/docs/concepts/models-and-orm/models */ module.exports = { attributes: { name: { type: 'string', required: true, }, price: { type: 'string', required: true, }, category: { type: 'string', required: true, }, author: { type: 'string', }, description: { type: 'string', }, }, }; |
Here we are defining the schema and the column names which will be there inside the table. We have the attributes object inside that we are defining all the schema and we are providing the dataTypes and also validation as well.
Now if we run this sails app using the below command as shown below
sails lift
If you run this above command it will automatically generate the migrations and it will create the table inside the database as shown below
Adding Records in MySQL
As you can see we are inserting a new book record using postman. Here we once again doing a post request providing the name and price of the book as form-data.
Now if you open the mysql database and table you will see an entry added inside the table
Connecting With MongoDB Database
Now we will be connecting the sails app with MongoDB Database we need to install the adapter library of sails as shown below
npm i sails-mongo
After installing this library you need to copy paste the below code inside the datastore.js file as shown below
1 2 3 4 5 6 7 8 9 10 11 |
module.exports.datastores = { default: { adapter: 'sails-mongo', port: '27017', host: 'localhost', database: 'db_books' }, }; |
Now execute the application by typing the below command as shown below
sails lift
After executing the above command it will create the migrations and the table will be created inside the Mongodb database.
Inserting Data in MongoDB Using Postman
We will be doing a simple post request inserting some data in postman as follows
As you can see we have created a new record with the values provided. Now if you check the MongoDB Database you will get a new record in that as shown below
To Get All the Records in MongoDB
Now to get all the records present in MongoDB we will issue a simple GET Request to the same url http://localhost:1337/product as shown below
And now for the update and delete operations we will be using the _id parameter. For update we will be using the put request and for the delete operation we will be using the delete request