온라인 쇼핑몰 예제 - 폴더,파일 구조(2)

Creating the dots·2021년 8월 31일
0

SQL

목록 보기
4/21

db > index.js

const mysql = require('mysql');
const dotenv = require('dotenv');
const config = require('../config/config);
dotenv.config();

const con = mysql.createConnection(
  config[process.env.NODE_ENV || 'development']
);

con.connect((err) => {
  if(err) throw err;
});

module.exports = con;  

models > index.js

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

module.exports = {
  orders: {
    get: (userId, callback) => {
      const sql = `SELECT o.id, o.created_at, o.total_price, i.name, i.price, i.image, oi.order_quantity FROM items as i
      INNER JOIN order_items as oi ON (oi.item_id = i.id)
      INNER JOIN orders as o ON (o.id = oi.order_id)
      WHERE (o.user_id = ?)`;
      const params = [userId];
      db.query(sql, params, (err, result) => {
        if (err) {
          return callback(err);
        } else {
          callback(null, result);
        }
      });
    },
    post: (userId, orders, totalPrice, callback) => {
      const sql = `insert into orders (user_id,total_price) values(?,?)`;
      const params = [userId,totalPrice];
      db.query(sql, params, (err, result) => {
        if (err) {
          callback(err);
        } else {
          const sql2 = `insert into order_items(order_id,item_id,order_quantity)values ?`;
          
          //method1 
          const params = [
            orders.map((order) => [result.insertId, order.itemId, order.quantity])
          ];
          db.query(sql2, params, (err, result)=>{
            if(err){callback(err)}
            else{callback(null,result)};
          });
          
          //method2
          const params = orders.map((el) => {
            return [result.insertId, el.itemId, el.quantity];
          });
          db.query(sql2, [params], (err, result) => {
            if (err) {
              callback(err);
            } else {
              callback(null, result);
            }
          });
        }
      });
    },
  },

  items: {
    get: (callback) => {
      const sql = `select * from items`;
      db.query(sql, (err, result) => {
        if (err) {
          callback(err);
        } else {
          callback(null, result);
        }
      });
    },
  },
};
profile
어제보다 나은 오늘을 만드는 중

0개의 댓글