Create Rest API Using Sequelize, babel and ES6 in NodeJs with PostgreSQL database

Rest API API Sequelize babel ES6 NodeJs PostgreSQL database

Sequelize

Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.

Babel

Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backward-compatible version of JavaScript in current and older browsers or environments. Here are the main things Babel can do for you:

  • Transform syntax
  • Polyfill features that are missing in your target environment (through @babel/polyfill)
  • Source code transformations (code mods)
  • And more! (check out these videos for inspiration)

PostgreSQL

PostgreSQL is a powerful, open-source object-relational database system with over 30 years of active development that has earned it a strong reputation for reliability, feature robustness, and performance.

 

Project Structure :

node_modules
    // node packages
SQL
   // db.sql
src
    controllers
      //  user.controller.js
    database
     //   database.js
    models
      //  user.js
    routes
      //  user.js
    app.js
    server.js
.babelrc
package.json
package-lock.json

Create a new directory, we can run the following command:

mkdir <project name>

then move into the newly created directory:

cd <project name>

then  run this command : 

npm init

and fill this information like that :

package name: (project name)
version: (1.0.0)
description:
entry point: (index.js) server.js
test command:
git repository:
keywords:
author:
license: (ISC) 

After creating project install node package run command:

npm install --save @babel/polyfill body-parser express morgan pg pg-hstore sequelize

install node dev dependencies package run command:

npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/node nodemon

create the .babelrc file and add this code :

{
    "presets": [
        "@babel/preset-env"
    ]
}

 open package.json and change "scripts"

"scripts": {
    "dev": "nodemon src/server.js --exec babel-node",
    "build": "babel src --out-dir dist",
    "start": "node dist/server.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  }

create the server.js file and add this code :

import app from './app';
import "@babel/polyfill"
async function main(){
await app.listen(process.env.PORT || 7557);
   console.log("server run on 7557");
}
main();

create the app.js file and add this code :

import express from 'express';
import bodyParser from 'body-parser';
import morgan from 'morgan';

//Importing Routes
import UserRoutes from './routes/user';

const app = express();

//middlewares
app.all('*', function(req, res, next) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
    res.header("Access-Control-Max-Age", "3600");
    res.header("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, x-access-token");
    next();
});

app.use(bodyParser.json({limit: '100mb'}));
app.use(bodyParser.urlencoded({limit: '50mb','extended': 'true'}));
app.use(bodyParser.json({type: 'application/vnd.api+json'}));

//routes
app.use('/api/user', UserRoutes)

export default app;

Create user.js in routes folder <project name>/src/routes/user.js and add this code :

import { Router } from 'express';
const router = Router();
import "@babel/polyfill"
import { createUser, getUser, getUsers, deleteUser, updateUsers } from '../controllers/users.controller';

router.post('/getUsers', getUsers);
router.post('/getUser', getUser);
router.post('/create', createUser);
router.delete('/removeUser', deleteUser);
router.put('/updateUser', updateUsers);

export default router;

Create user.js in models folder <project name>/src/models/user.js and add this code :

import Sequelize from 'sequelize';
import { sequelize } from '../database/database'

const User = sequelize.define('users', {
id:{
   type:Sequelize.INTEGER,
   primaryKey:true
},
name:{
    type: Sequelize.STRING
},
email:{
    type: Sequelize.STRING,
    unique: true
},
password:{
    type: Sequelize.STRING
},
phone:{
   type: Sequelize.STRING,
   unique: true
},
profile_pic:{
    type: Sequelize.STRING
}
},{
   timestamps:false
});

export default User;

Create users.controller.js in models folder <project name>/src/models/users.controller.js and add this code :

import User from '../models/users';
import Sequelize from 'sequelize';
const Op = Sequelize.Op;

export async function getUsers(req, res) {
try{
   let getdata = await User.findAll(req.body);
   if(getdata){
        res.json({
            success: true,
            message:"User Fetch Successfully",
            data:getdata
        });
    }
}catch(err){
    console.log(err);
    res.status(500).json({
         success: false,
         message:"Something went wrong!"
    })
}
}

export async function getUser(req, res) {
  try{
      let createdata = await User.findOne({ where: req.body});
      if(createdata){
          res.json({
             success: true,
             message:"User fetch Successfully",
             data:createdata
         });
      }
   }catch(err){
      console.log(err);
      res.status(500).json({
          success: false,
          message:"Something went wrong!"
     })
  }
}

export async function createUser(req, res) {
    try{
       let checkdata = await User.findOne({where:{email:req.body.email}});
       if(checkdata){
            res.json({
                message:"Already Exist",
                data:checkdata
            });
       }else{
           let createdata = await User.create(req.body, {fields: ['name', 'email', 'password', 'phone', 'profile_pic']});
           if(createdata){
                res.json({
                  success: true,
                  message:"User Created Successfully", 
                  data:createdata
                });
           }
       }
     }catch(err){
         console.log(err);
         res.status(500).json({
             success: false,
             message:"Something went wrong!"
         })
     }
}

export async function deleteUser(req, res) {
    try{
        let deletedata = await User.destroy({where:{id:req.body.id}});
        if(deletedata){
            res.json({
                 success: true,
                 message:"User Created Successfully",
                 data:deletedata
            });
        }
    }catch(err){
          res.status(500).json({
               success: false,
               message:"Something went wrong!"
          })
    }
}

export async function updateUsers(req, res) {
    try{
       let finddata = await User.findAll({where:{id:req.body.id}});
       if(finddata.length > 0){
           finddata.forEach(async data =>{await data.update(req.body)})
       }
       return res.json({
            success: true,
            message:"User Created Successfully",
            data:finddata
       });
     }catch(err){
         console.log(err);
         res.status(500).json({
             success: false,
             message:"Something went wrong!"
         })
     }
}

Create database.js in models folder <project name>/src/models/database.js and add this code :

import Sequelize from 'sequelize';

export const sequelize = new Sequelize(
'postgres://postgres:8857@localhost:5432/postgres', {
   host:"localhost",
   dialect:'postgres',
   pool:{
         max:5,
         min:0,
         idle:10000
   },
   logging: false
 });

sequelize.authenticate().then(() => {
     console.log('Connection has been established successfully.');
}).catch(err => {
     console.error('Unable to connect to the database:', err);
});

Rest API Using  Sequelize, babel and ES6 in NodeJs with PostgreSQL database Done.

Run command

npm run dev // development server with babel-node
npm start // development server
npm test // testing server
npm run build // create dist folder for producation 

Thank you

Github link: https://github.com/Sudarshan101/postgresCurlApi

Youtube: https://www.youtube.com/watch?v=DGPiobWlwSw

 

 

About the author
Code solution

info@codesolution.co.in

Discussion
  • 0 comments

Add comment To Login
Add comment