{ sailsit }

Sails Js Tutorials for Beginners and Forum

Have a Question?

If you have any question you can ask below or enter what you are looking for!

Simple CRUD Operations – REST API

1. Setting up SailsJS Environment

First you need to setup Sails project. You can follow the guide on Sails official website Getting Started with SailsJS

2. Creating Project

Run this command in any directory

sails create sails-crud-simple

This command will create new project with all the required dependencies

3. Setting up database

As we are going to use mongoDB with this application, you need to install sails-mongo adapter from npm. Use below command to install sails-mongo adapter.

npm install sails --save-mongo

Note: Run this command in your project root directory

To connect your sails application with mongoDB, paste the below code snippet in config/connections.js file

mongoDB: {
   adapter: 'sails-mongo',
   host: 'localhost', //Add your host
   port: '27017',
   user: '', //Optional
   password: '', //Optional
   database: 'sails-crud-simple'
}

Now we need to define the above created connection in config/models.js. You can define connection in models.js by using this line of code

connection: 'mongoDB' //This name should be exactly same as the name given in config/connection.js

With this we have completed the setup of our sails application.
Let’s get started with coding our application

4. Creating Models & Controllers

A model in sails application defines your schema definition for your DB
Let’s create a model name Student.
To create a model use this command

sails generate model Student

Now, let’s create a controller.
A Controller in sails application receives request via routes.
To create a controller use this command

sails generate controller Student

 

5. Defining Schema in Model

You can define all the required information about the model. As in our case, we are using Student model in which we can define student information.
You can get the Student model definition below which we will be using in this tutorial.

module.exports = {

    tableName: "student" //Collection name,
    attributes: {
        id: {
            type: 'integer',
            primaryKey: true
        },
        student_id: {
            type: 'integer',
            unique: true,
            autoIncrement: true
        },
        name: {
            type: 'string'
        },
        email: {
            type: 'string'
        },
        phone: {
            type: 'integer'
        },
        department: {
            type: 'string'
        }
    }
};

 

6. Creating Functions in Controller for CRUD Operations
i. CREATE

We will write a function, which will take input from request object and create a new record in our DB

create: function (req, res) {

    //Reading input from request object
    let name = req.param("name");
    let email = req.param("email");
    let phone = req.param("phone");
    let department = req.param("department");
    let studentId = req.param("student_id");

    //Inserting record in mongoDB
    Student.create({
        name: name,
        email: email,
        phone: phone,
        department: department,
        student_id: studentId
    }).then(function (student) {
        //Returning success response
        return res.send({
            "success": true,
            "message": "Record created successfully",
            "data": student
        });
    }).catch(function (err) {
        sails.log.debug(err);
        //Returning failure response
        return res.send({
            "success": false,
            "message": "Unable to create record"
        });
    });
},

 

ii. READ

Read function will fetch all the records available in our mongoDB (student collection)

get: function (req, res) {

    Student.find()
        .then(function (students) {
            if(!students || students.length == 0) {
                return res.send({
                    "success": false,
                    "message": "No records found in DB"
                });
            }

            return res.send({
                "success": true,
                "message": "Records fetched",
                "data": students
            });
        })
        .catch(function (err) {
            sails.log.debug(err);
            return res.send({
                "success": false,
                "message": "Unable to fetch records"
            });
        });
},

 

iii. UPDATE

Update function will get input, and updates the record by finding the record using the input student_id

update: function (req, res) {

    let studentId = req.param("student_id");
    let name = req.param("name");
    let email = req.param("email");
    let phone = req.param("phone");
    let department = req.param("department");

    //Update function takes two object input,
    //1. key:value pair for searching the record
    //2. key:value pairs for updating the records
    Student.update({student_id: studentId}, {name: name, email: email, phone: phone, department: department})
        .then(function (student) {
            return res.send({
                "success": true,
                "message": "Record updated",
                "data": student
            });
        })
        .catch(function (err) {
            sails.log.debug(err);
            return res.send({
                "success": false,
                "message": "Unable to update record"
            });
        });
},

 

iv. DELETE

Delete function will take student_id as input and deletes the record for that student_id from DB

delete: function (req, res) {

    let studentId = req.param("student_id");

    //Delete function takes key:value pair by which it will search and delete the record
    Student.destroy({student_id: studentId})
        .then(function (student) {
            return res.send({
                "success": true,
                "message": "Record deleted successfully",
                "data": student
            });
        })
        .catch(function (err) {
            sails.log.debug(err);
            return res.send({
                "success": false,
                "message": "Unable to delete record"
            });
        });
}

All the required functions for CRUD are ready. Let’s bind this functions with routes

7. Binding Controller with Routes

Now we will create routes in config/routes.js file, which will point to specific functions of controller.
Routes are the entry point for sails application, so each function should have unique routes.
Below are the four routes which are bind to the four CRUD functions of controller.

'POST /api/student/create': 'StudentController.create',
'GET /api/student/get': 'StudentController.get',
'POST /api/student/update/:student_id': 'StudentController.update',
'DELETE /api/student/delete/:student_id': 'StudentController.delete'

This last step completes our sails application.

8. Running Sails Application

To run your application go to root directory of your project and run the below command

sails lift

This will start your sails server on port: 1337
You can access all your api’s at
http://localhost:1337/{your_route}

You can also download the complete project from the below github url
SailsCRUDSimple

You can test all API’s using any REST Client available (Recommended: POSTMAN)

Leave your QUESTIONS in comment box!!

One Comment

  1. Pingback: Sails – Unit Testing with Mocha.js – SailsIt

Comments are closed.