npm i --save sequelize

Nous allons devoir redéfinir notre database.js :

const Sequelize = require("sequelize");
const sequelize = new Sequelize('node_complete', 'root', '', {
    dialect: 'mysql',
    host: 'localhost',
    port: '3308'
});

module.exports = sequelize;

Maintenant qu'on utilise Sequelize il va falloir modifier notre models/products.js :

Sequelize nous permet de définir la composition de notre rows sql

const Sequelize = require("sequelize");
const sequelize = require("./../util/database");

const Product = sequelize.define('product', {
  //fiels in mysql :
  id: {
// type of
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true
  },
// if there's only one value, this syntax is correct
  title: Sequelize.STRING,
  price: {
    type: Sequelize.DOUBLE,
    allowNull: false
  },
  imageUrl: {
    type: Sequelize.STRING,
    allowNull: false
  },
  description : Sequelize.TEXT
});

module.exports = Product;

SYNC SEQUELIZE TO DATABASE :

Maintenant on va se rendre dans notre app.js


const sequelize = require('./util/database');

...

// syncs the models to the database
sequelize.sync().then(result => {
    app.listen(3000);
    console.log(result)
}).catch(err => {
    console.log(err)
});

Et modifier les fichiers ou l'on appelait auparavant les méthodes de Product :

// models/admin.js

exports.postAddProduct = (req, res, next) => {
  const title = req.body.title;
  const imageUrl = req.body.imageUrl;
  const price = req.body.price;
  const description = req.body.description;

  Product.create({
    title: title,
    imageUrl: imageUrl,
    price: price,
    description: description
  })
  .then(result => {
    console.log(result)
  })
  .catch(err => {
    console.log(err)
  }) 
};

RETRIEVE DATA AND FIND PRODUCTS

Nous allons modifier nos autres méthodes :

// get the product by id we use "findByPk"
exports.getEditProduct = (req, res, next) => {
  const editMode = req.query.edit;
  if (!editMode) {
    return res.redirect('/');
  }
  const prodId = req.params.productId;

  Product.findByPk(prodId).then(
    product => {
      if (!product) {
        return res.redirect('/');
      }
      res.render('admin/edit-product', {
        pageTitle: 'Edit Product',
        path: '/admin/edit-product',
        editing: editMode,
        product: product
      });
    }
  ).catch(err => {console.log(err)})
};

// or we can use a where research : 
exports.getProduct = (req, res, next) => {
  const prodId = req.params.productId;
// attention la methode avec where retourne TOUJOURS UN ARRAY !
  Product.findAll({where: {
    id: prodId
  }}).then(products => {
      res.render('shop/product-detail', {
        product: products[0],
        pageTitle: products.title,
        path: "/products"
      })
    })
    .catch(err => { console.log(err) })

  // Product.findByPk(prodId)
  // .then(product => {
  //   res.render('shop/product-detail', {
  //     product: product,
  //     pageTitle: product.title,
  //     path: "/products"
  //   })
  // })
  // .catch(err => { console.log(err) })
};

//get all products we use "findAll"
exports.getProducts = (req, res, next) => {
  Product.findAll().then((products) => {
    console.log('products fetched ')
    res.render('admin/products', {
      prods: products,
      pageTitle: 'Admin Products',
      path: '/admin/products'
    });
  }).catch(err => { console.log(err) })
};

Et pour update ?

exports.postEditProduct = (req, res, next) => {
  const prodId = req.body.productId;
  const updatedTitle = req.body.title;
  const updatedPrice = req.body.price;
  const updatedImageUrl = req.body.imageUrl;
  const updatedDesc = req.body.description;

  Product.update({
    title: updatedTitle,
    imageUrl: updatedImageUrl,
    price: updatedPrice,
    description: updatedDesc
  }, {
    where: {
      id: prodId
    }
  }).then(result => {
    console.log(result);
    res.redirect("/admin/products")
  }).catch(err => {
    console.log(err)
  })
};

Et pour le delete on utilise destroy :

exports.postDeleteProduct = (req, res, next) => {
  const prodId = req.body.productId;
  Product.destroy({where: {
    id: prodId
  }}).then(
    res.redirect("/products")
  ).catch(err => {
    console.log(err)
  });
};

ADDING ONE-TO-MANY RELATIONSHIPS