NodeJS + Express + Sequelize + CRUD – 2/2

Nodejs + Express

Controller

const controller = {} 

// import model
var Customers = require('./models/Customers');
var Countries = require('./models/Countries');

const { Op } = require("sequelize");
  
controller.create = async ( req, res ) => {

  try {

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

    res.json(response);

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

}

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

  try {

    const response = await Customers.findAll({
      include: [ Countries ]
      // include: [{
      //   model: Countries,
      //   where: { name: "Colombia" }
      // }]
    })
    .then(function(data){
      const res = { success:true, message: "Load successful", data: data}
      return res;
    })
    .catch(error=>{
      const res = { success: false, error: error }
      return res
    })

    return res.json(response);

  } catch (e) {
    console.log("Error controller.list");
    console.log(e);
  }
}

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

  try {

    const response = await Countries.findAll({
      // where: { id: 1 },
      include: [ "customers" ]
      // include:[
      //   {
      //     model : Customers,
      //     attributes: [ 'id', 'name' ],
      //     // where: { email: "[email protected]" },
      //   }
      // ]
    })
    .then(function(data){
      console.log(data);
      const res = { success:true, message: "Load successful", data: data}
      return res;
    })
    .catch(error=>{
      const res = { success: false, error: error }
      return res
    })

    return res.json(response);

  } catch (e) {
    console.log("Error controller.list");
    console.log(e);
  }
}

module.exports = controller;

Sequelize

Model

src/models/Countries.js

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

var Countries = sequelize.define('countries',{
  code:{
    type: Sequelize.STRING,
    primaryKey: true
  },
  name: Sequelize.STRING,
},
{
	 timestamps: false,
});
 
module.exports = Countries;

src/models/Customers.js

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

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,
  countryCode:{
    type: Sequelize.STRING,
    references: {
      model: Countries,
      key: 'code'
    }
  }
});

module.exports = Customers;

Customers.belongsTo(Countries, {
  foreignKey: 'countryCode', targetKey: 'code'
});

Countries.hasMany(Customers,{
  as: 'customers'
})

SQL script

INSERT INTO tutofox.countries (code,name) VALUES 
('CO','Colombia'),
('ES','España'),
('MX','Mexico'),
('US','Estados Unidos de América');

Deja una respuesta

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