Rest APIs example with Sequelize ORM with Node.js and Express

This article assumes you have a fair knowledge of the basic setup of project and connection sequelize database.

Let's make a sequelize-app Node application and install Sequelize. First off all,create a directory for our project, enter it, and create a project with the default settings:

$ mkdir sequelize-app 
$ cd sequelize-app

Initialize a NodeJS application by running the following command:

$ npm init -y

This will create a package.json file with a basic config. You can manually add the configuration by omitting the -y flag.

Next we'll create the application file with a basic Express server. Let's call it app.js to and run the following command line within the project folder.

$ npm i express

Add the following codes in the newly created app.js file

const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');


// router import
const user = require('./routes/user')




const app = express();


app.use(express.json())
app.use(morgan('tiny'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));


// Routing
app.use('/api', user)


// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to  application." });
});



// set port, listen for requests
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});

Morgan is a HTTP request logger middleware for Node. js. It simplifies the process of logging requests to your application

$ npm i morgan

In order to get access to the post data we have to use body-parser . Basically what the body-parser is which allows express to read the body and then parse that into a Json object that we can understand

$ npm install body-parser

When we make changes, we'll have to kill the process and restart to see the effect. So, we'll install a package that will save us that stress: Nodemon

$ npm i nodemon

Edit scripts in package.json file to look like this:

"scripts": {
    "start": "nodemon app.js"
  },

Sequelize Setup in Express JS App
In this article I will be using Postgres DB but you can use any DB you are comfortable with such as MySQL, SQLite, etc.

$ npm install -g sequelize-cli

$ npm install sequelize-cli

Install Sequelize and Postgres packages by running the command:

$ npm i sequelize pg

Next, we initialize Sequelize in the project.

$ sequelize init

The command creates the necessary folders and files for Sequelize ORM.

If you look at sequelize-app/models/index.js,Let's look the snnipet

'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

Create a DB and update the config/config.json file accordingly:
We really care about development process change username, password and database,dialect name don't headache other process

{
  "development": {
    "username": "dream99",
    "password": "dream99",
    "database": "sequlizeApp",
    "host": "127.0.0.1",
    "dialect": "postgres"
  },
  "test": {
    "username": "root",
    "password": null,
    "database": "database_test",
    "host": "127.0.0.1",
    "dialect": "postgres"
  },
  "production": {
    "username": "root",
    "password": null,
    "database": "database_production",
    "host": "127.0.0.1",
    "dialect": "postgres"
  }
}

All is now set to create models and migration.
Let's create a model and migration for users.

Run the command:

npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string

This command creates a User model and migration table in the corresponding folders. The attributes are the fields we want to have on the table.

The user model looks like this:

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class User extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
  };
  User.init({
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING,
    email: DataTypes.STRING
  }, {
    sequelize,
    modelName: 'User',
  });
  return User;
};

Next, we run the migration to create the DB tables:

sequelize db:migrate

And migrations like this:

'use strict';
module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('Users', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      firstName: {
        type: Sequelize.STRING
      },
      lastName: {
        type: Sequelize.STRING
      },
      email: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable('Users');
  }
};

Suppose we want to insert some data into a few tables by default. Seed files are some change in data that can be used to populate database table with sample data or test data.

Let's create a seed file which will add a demo user to our User table following command:

$ npx sequelize-cli seed:generate --name demo-user

Seed file look like this :

'use strict';
module.exports = {
  up: async (queryInterface, Sequelize) => {



      await queryInterface.bulkInsert('Users', [{
        firstName: 'John',
        lastName: 'Doe',
        email: '[email protected]',
        createdAt: new Date(),
        updatedAt: new Date()
      }], {});

  },

  down: async (queryInterface, Sequelize) => {

      await queryInterface.bulkDelete('Users', null, {});

  }
};

In last step you have create a seed file. It's still not committed to database. To do that we need to run a simple command.

$ npx sequelize-cli db:seed:all

Our database is now created.Now let's make Route and Controllers
Create a controllers folder in sequelize-app and add user.js file to it. That's where our user management logic will reside.
Add the following code to create user controller with logic:

const User = require('../models').User





module.exports = {

    // create account
    signUp: (req, res) => {
       let { firstName, lastName, email} = req.body
       User.create({
           firstName,
           lastName,
           email
       }).then((user) => {
           return res.status(201).json({
               "message": "User created successfully",
                user
           }).catch(err => {
               return res.status(400).json({err})
           })
       })
    },

    updateSignUp: (req, res) => {
        let { firstName, lastName, email} = req.body
        let id = req.params.id

        User.findOne({
            where: {id:id}
        }).then( user => {
            if (user){
                user.update({firstName, lastName, email})
                .then((updateUser) => {
                    return res.status(202).json({
                        "message": "User updated successfully",
                         updateUser
                    })
                })
            }else{
                return res.status(206).json({
                    "message": "User not found"
                })
            }
        }).catch(error => {
            return res.status(400).json({
                "error": error
            })
        })
    },


    // get all users

    getAllUsers: ( req, res ) => {

        User.findAll( {
            attributes: ['id', 'firstName', 'lastName', 'email'],
            limit: 5,
            order: [['id', 'DESC']]
        }).then(users => {
            return res.status(200).json({
                users
            })
        }).catch(err => {
            return res.status(400).json({err})
        })
    },

    // get single user by id

    getSingleUser:(req, res) => {
        let id = req.params.id

        User.findByPk(id)
        .then((user) => {
            return res.status(200).json({user})
        }).catch(err => {
            return res.status(400).json({err})
        })
    },

// delete user by id

deleteSingleUser: (req, res) => {
    let id = req.params.id

    User.destroy({
        where: {id: id}
    }).then(() =>{
        return res.status(200).json({
            "message": "User Deleted successfully"
        })
    }).catch(err =>{
        return res.status(400).json({error})
    })

},

// delete all users

deleteAllUsers: (req, res) => {
    User.destroy({
        truncate: true
      }).then(() => {
        return res.status(200).json({
            success: true,
            "message": "All Users deleted"
        })
      }).catch(err => {
          return res.status(400).json({
              err
          })
      })
},






}

Create the routes folder with user.js file inside and add the following code:

const express = require('express')
const router = express.Router()
const {
     signUp,
     updateSignUp ,
     getAllUsers,
     getSingleUser,
     deleteSingleUser,
     deleteAllUsers,

    } = require('../controllers/user')

// -------------------------CUSTOM ROUTE-------------------------
router.post('/sign-up',
    signUp
)

router.put('/sign-up/:id',
    updateSignUp
)

router.get('/sign-up/',
    getAllUsers
)

router.get('/sign-up/:id',
getSingleUser
)

router.delete('/sign-up/:id',
deleteSingleUser
)

router.delete('/sign-up/',
deleteAllUsers
)



// -------------------------EXPORT ROUTER-------------------------
module.exports = router

Let's take a look at some static images postman:
Get All user:
Alt Text
Get single user:
Alt Text
Actually this is basic set-up of Express JS REST API, Postgres, and Sequelize ORM

If you have any information you can comment below please.Happy coding...
Feel free to check out the code on:
https://github.com/Julfikar-Haidar/sequelize-app

21