Schedules_date.js 2.55 KB
const express = require("express");
const { pool } = require("../libs/MySQL");
const schedules_dateRouter = express.Router();

async function route() {
  // (userID, date) => schedules
  schedules_dateRouter.get("/", async (req, res) => {
    // console.log("/db/schedules_date");
    const connection = await pool.getConnection(async (con) => con);
    try {
      const queryString = `
      SELECT sc.label, sc.type, sc.description, sc.url, sc.detail,
        sbj.name, us.nickname, us.color, sc.uid, "schedules_date" \`table\`
      FROM schedules_date sc
      INNER JOIN \`user-subject\` us
        ON sc.userID = us.userID
        AND sc.subjectID = us.subjectID
        AND us.status = 1
      INNER JOIN subjects sbj
        ON sc.subjectID = sbj.ID
      WHERE sc.date = "${req.query.date}"
        AND sc.userID = ${req.query.userID}
        AND sc.status = 1`;
      const [results] = await connection.query(queryString);
      res.send(results);
    } catch (e) {
      console.log(e);
      res.end();
    } finally {
      connection.release();
    }
  });

  // (userID, label, subjectID, type, description, url, date)
  schedules_dateRouter.post("/", async (req, res) => {
    console.log("post /db/schedules_date");
    const connection = await pool.getConnection(async (con) => con);
    try {
      await connection.beginTransaction();
      let queryString = `
      INSERT INTO \`schedules_date\`
        (userID, label, subjectID, type, description, url, date, status)
      VALUES (${req.body.userID}, "${req.body.label}", ${req.body.subjectID}, "${req.body.type}",
        "${req.body.description}", "${req.body.url}", "${req.body.date}", 1);`;
      await connection.query(queryString);

      queryString = `UPDATE \`schedules_date\`
      SET uid = -ID
      WHERE ID = LAST_INSERT_ID();`;
      await connection.query(queryString);

      queryString = `      
      SELECT sc.label, sc.type, sc.description, sc.url, sc.detail,
      sbj.name, us.nickname, us.color, sc.uid, "schedules_date" \`table\`
      FROM schedules_date sc
      INNER JOIN \`user-subject\` us
        ON sc.userID = us.userID
        AND sc.subjectID = us.subjectID
        AND us.status = 1
      INNER JOIN subjects sbj
        ON sc.subjectID = sbj.ID
      WHERE sc.ID = LAST_INSERT_ID()`;
      [results] = await connection.query(queryString);
      await connection.commit();
      res.send(results[0]);
    } catch (e) {
      console.log(e);
      await connection.rollback();
      res.end();
    } finally {
      connection.release();
    }
  });
}
route();

module.exports = schedules_dateRouter;