Subjects.js 1.48 KB
const express = require("express");
const { pool } = require("../libs/MySQL");
const subjectsRouter = express.Router();

async function route() {
  // (ID) => null | name  //unused
  subjectsRouter.get("/", async (req, res) => {
    console.log("/db/subjects");
    const connection = await pool.getConnection(async (con) => con);
    try {
      const queryString = `
      SELECT name FROM subjects sbj
        WHERE sbj.ID = ${req.query.ID}`;
      const [results] = await connection.query(queryString);
      res.send(results.length && results[0].name);
    } catch (e) {
      console.log(e);
      res.end();
    } finally {
      connection.release();
    }
  });

  // [{name, link}, ...]
  subjectsRouter.post("/s", async (req, res) => {
    console.log("post /db/subjects/s");
    const connection = await pool.getConnection(async (con) => con);
    try {
      await connection.beginTransaction();
      const subList = [];
      for (const s of req.body.list) {
        const subjectID = s.link.split("courses/")[1];
        const queryString = `
        INSERT IGNORE INTO subjects
          (ID, name)
        VALUES (${subjectID},' ${s.name}')`;
        await connection.query(queryString);
        subList.push({ name: s.name, subjectID });
      }
      await connection.commit();
      res.send(subList);
    } catch (e) {
      console.log(e);
      await connection.rollback();
      res.end();
    } finally {
      connection.release();
    }
  });
}
route();

module.exports = subjectsRouter;