NodeJS + Express + React Hooks + MySQL – #3 Model + Sequelize

NodeJS + Express

Sequelize

npm install --save sequelize

MySQL

npm install --save mysql2

Database

src/models/database.js

var Sequelize = require('sequelize');

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

database.sync()

module.exports = database;

Model Customer

src/models/Customers.js

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

var Customers = database.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/controllers/CustomerController.js

const controller = {}
// import model
var Customers = require('../models/Customers');

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

  // const data = {
  //   success: true,
  //   message: "Developed by Artyom"
  // }
  // res.json(data);

  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);

};

module.exports = controller;

Routes

src/routes/api.js

const express = require('express');
const router = express.Router();
//import controller
const customerController = require('./../controllers/CustomerController');

router.get('/customer/test', customerController.testApi );

module.exports = router;

Server

src/server.js

app.use('/api',require("./routes/api"));

Sequelize

Deja una respuesta

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