Rest API CRUD – Node.js + express + React.js + MySQL Part 2: Model – Sequelize

Vamos a crear dos modelos para empleado y role. Y luego trabajamos con la ORM sequelize.

Video

Sequelize

Sequelize es un ORM Node.js basado en promesas para Postgres, MySQL, MariaDB, SQLite y Microsoft SQL Server.

Instalar sequelize

npm install --save sequelize

Modelo

Crear una carpeta «model» y luego un archivo llamado database.js para conexiones de base de datos

src/model/mysql.js

var Sequelize = require('sequelize');

const sequelize = new Sequelize(
  'node',
  'admin',
  'password',
  {
    host: 'localhost',
    dialect: 'mysql'
  }
);

module.exports = sequelize;

Crear dos modelos

src/model/Role.js

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

var Role = sequelize.define('role', {
  role: Sequelize.STRING
},
{
	 timestamps: false,
});

module.exports = Role

src/model/Employee.js


//import sequelize
var Sequelize = require('sequelize');
// importing connection database
var sequelize = require('./database');
// import model for FK roleID
var Role = require('./Role');

var Employee = sequelize.define('employee', {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true,
  },
  name: Sequelize.STRING,
  email: Sequelize.STRING,
  address: Sequelize.STRING,
  phone: Sequelize.BIGINT,
  roleId: {
    type: Sequelize.INTEGER,
    // This is a reference to another model
    references: {
      model: Role,
      key: 'id'
    }
  }
},
{
	 timestamps: false,
});

Employee.belongsTo(Role)

module.exports = Employee

Routes

src/routes/EmployeeRoute.js

router.get('/testdata',EmployeeController.testdata );
router.get('/list',EmployeeController.list );

Controlador

src/controllers/EmployeeController.js

Importarlos los modelos y base de datos.

var Employee = require('../model/Employee');
var Role = require('../model/Role');
var sequelize = require('../model/database');

Agregar dos funciones de testdata y list

controllers.testdata = async ( req, res) => {
  
  const response = await sequelize.sync().then(function() {
     const data =  Employee.findAll()
     return data;
  })
  .catch(err => {
    return err;
  });
  res.json(response)

}

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

    const data = await Employee.findAll();
    res.json(data)

}

Sequelize query

Crear dos create para Role y Employee

//Create role
Role.create({
     role:  'Admin'
 });

// create employee
Employee.create({
     name: 'Malena Morgan',
     email:  'malena@mail.com',
     address: 'California Cll 108',
     phone: '123456789',
     roleId:1
 });

Añadir un comentario

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