Node.js Mysql 데이터 출력 기초

이건선·2023년 1월 30일
0

Node.js

목록 보기
11/32

👉 mysql.createPool

// util/database.js

const mysql = require("mysql2");

const pool = mysql.createPool({
  host: "localhost",
  user: "root",
  database: "node-complete", // schma name
  password: "*************", // password
});

module.exports = pool.promise();


🧐 pool

promise를 사용함으로써 콜백 대신 비동기적 태스크, 비동기적 데이터를 다룰 수 있게 된다.


👉 M product.js 변경


const db = require("../util/database");

const Cart = require("./cart");

module.exports = class Product {
  constructor(id, title, imageUrl, description, price) {
    this.id = id;
    this.title = title;
    this.imageUrl = imageUrl;
    this.description = description;
    this.price = price;
  }

  save() {
    return db.execute(
      "INSERT INTO products (title, price, imageUrl, description) VALUES (?,?,?,?)",
      [this.title, this.price, this.imageUrl, this.description]
    );
  }

  static deleteById(id) {}

  static fetchAll() {
    return db.execute("SELECT * FROM products");
  }

  static findById(id) {
    return db.execute("SELCET * FROM products WHERE product.id = ?", [id]);
  }
};

🧐 execute가 반환하는 전체 promise

fetchAll이 promise를 반환하게 된다.



👉 C shop.js 변경


const Product = require("../models/product");
const Cart = require("../models/cart");

exports.getProducts = (req, res, next) => {
  Product.fetchAll()
    .then(([rows]) => {
      res.render("shop/product-list", {
        prods: rows,
        pageTitle: "All Products",
        path: "/products",
      });
    })
    .catch((err) => console.log(err));
};

exports.getProduct = (req, res, next) => {
  const prodId = req.params.productId;
  Product.findById(prodId)
    .then(([product]) => {
      console.log(product);
      res.render("shop/product-detail", {
        product: product[0],
        pageTitle: product.title,
        path: "/products",
      });
    })
    .catch((err) => console.log(err));
};

exports.getIndex = (req, res, next) => {
  Product.fetchAll()
    .then(([rows, fieldData]) => {
      res.render("shop/index", {
        prods: rows,
        pageTitle: "Shop",
        path: "/",
      });
    })
    .catch((err) => console.log(err));
};

...

🧐 제품 가져오기

Product.fetchAll().then() rows와 fieldData로 끌어오는 구문을 여기 사용한다. 이름은 자유롭게 설정해도 되고, rows 이 부분의 인수 데이터가, 중첩된 배열의 첫 번째 요소가 될 것이고 fieldData가 두 번째 요소가 된다. 이렇게 두 중첩된 배열을 단순히 포함하는 두 변수를 사용할 수 있습니다

profile
멋지게 기록하자

0개의 댓글