NodeJS + Express + Sequelize + CRUD

Nodejs + Express

mkdir project-folder
npm init --yes
// express
npm install express

src/server.js

const express = require('express');
const app = express();

//Settings
app.set('port', process.env.PORT || 3000);

//Middlewares
app.use(express.json());

app.use('/',(req,res)=>{
  res.send("Hello World form NodeJS express.");
});


app.listen(app.get('port'),()=>{
  console.log("Start server on port "+app.get('port'))
})

Run server

node src/server.js

Nodemon

sudo npm install --g nodemon

package.json

"dev":"nodemon src/app.js"

Run server with nodemon

npm run dev

Controller

src/controller.js

const controller = {}

controller.index = (req,res) => {

  const data = {
    name: "Jhon Smith",
    age: 20,
    city: 'London'
  }

  res.json(data);
};

module.exports = controller;

Route

src/routes.js

var express = require('express');
var route = express();
// import controller
const controller = require('./controller')
// create route
route.get('/index',controller.index);
// exprot route
module.exports = route;

src/server.js

const routes = require('./routes');
app.use('/test', routes);

Sequelize

npm install --save sequelize

MySQL

npm install --save mysql2

MariaDB

npm install mariadb

PostgreSQL

npm install pg

https://sequelize.org/master/manual/dialect-specific-things.html

Database

src/database.js

var Sequelize = require('sequelize');

const database = new Sequelize(
  'tutofox', // name database
  'admin', // user database
  'Mn2020sm#', // password database
  {
    host: 'localhost',
    dialect: 'mysql' // mariadb / sqlite / postgres
  }
);

database.sync()

module.exports = database;

Model

src/models/Customers.js

//import sequelize
var Sequelize = require('sequelize');
// importing connection database
var sequelize = require('../database');

var Customers = sequelize.define('customers', {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true,
  },
  name: Sequelize.STRING,
  email: Sequelize.STRING,
  address: Sequelize.STRING,
  phone: Sequelize.BIGINT
});

module.exports = Customers

Controller

src/controller.js

//import sequelize
var Sequelize = require('sequelize');
// imporconst controller = {}
// import model
var Customers = require('./models/Customers');
const { Op } = require("sequelize");

controller.index = (req,res) => {

  const data = {
    name: "Jhon Smith",
    age: 20,
    city: 'London'
  }

  res.json(data);
};

//

controller.list = async (req, res) => {

  const response = await Customers.findAll()
  .then(function(data){
    const res = { success: true, data: data }
    return res;
  })
  .catch(error =>{
    const res = { success: false, error: error }
    return res;
  })
  res.json(response);

}

controller.create = async ( req, res) =>{

  try {

    const response = await Customers.create({
      name:"John Smith",
      email:"[email protected]",
      address:"Cll 100 Malibu",
      phone:"123456789"
    })
    .then(function(data){
      const res = { success: true, data: data, message:"created successful" }
      return res;
    })
    .catch(error=>{
      const res = { success: false, error: error }
      return res;
    })
    res.json(response);

  } catch (e) {
    console.log(e);
  }
}

controller.update = async ( req, res) =>{

  try {

    const id = 19;

    const response = await Customers.update({
      name:"Jhon Milan",
      email:"[email protected]",
      address:"Cll 100 California",
      phone:"123456789"
    },{
      where: { id: id}
    })
    .then(function(data){
      const res = { success: true, data: data, message:"updated successful" }
      return res;
    })
    .catch(error=>{
      const res = { success: false, error: error }
      return res;
    })
    res.json(response);

  } catch (e) {
    console.log(e);
  }
}

controller.get = async ( req, res) =>{

  try {

    const { id } = req.params;

    const response = await Customers.findAll({
      where: { id: id}
      // where: { id: [ 1, 2, 4 ] }
      // like: { name: "Milan" }
      // where: {
      //   name: {
      //     [Op.like]: '%Milan%'
      //   }
      // }
    })
    .then( function(data){
      const res = { success: true, data: data }
      return res;
    })
    .catch(error => {
      const res = { success: false, error: error }
      return res;
    })
    res.json(response);

  } catch (e) {
    console.log(e);
  }
}


controller.delete = async ( req, res) =>{

  try {

    const { id } = req.params;

    const response = await Customers.destroy({
      where: { id: id }
    })
    .then( function(data){
      const res = { success: true, data: data, message:"Deleted successful" }
      return res;
    })
    .catch(error => {
      const res = { success: false, error: error }
      return res;
    })
    res.json(response);

  } catch (e) {
    console.log(e);
  }
}

module.exports = controller;
ting connection database
var sequelize = require('../database');

var Customers = sequelize.define('customers', {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true,
  },
  name: Sequelize.STRING,
  email: Sequelize.STRING,
  address: Sequelize.STRING,
  phone: Sequelize.BIGINT
});

module.exports = Customers

Route

src/routes.js

var express = require('express');
var route = express();
// import controller
const controller = require('./controller')
// create route
route.get('/index',controller.index);
route.get('/list',controller.list);
route.get('/create',controller.create);
route.get('/update',controller.update);
route.get('/get/:id',controller.get);
route.get('/delete/:id',controller.delete);

// exprot route
module.exports = route;

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *