Subjects.js 1.27 KB
const express = require("express");
const mysql2 = require("mysql2/promise");
const { connectOption } = require("../libs/MySQL");
const subjectsRouter = express.Router();

async function route() {
  const connection = await mysql2.createConnection(connectOption);

  // (ID) => null | name  //unused
  subjectsRouter.get("/", async (req, res) => {
    console.log("/db/subjects");
    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();
    }
  });

  // [{name, link}, ...]
  subjectsRouter.post("/s", async (req, res) => {
    console.log("post /db/subjects/s");
    try {
      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 });
      }
      res.send(subList);
    } catch (e) {
      console.log(e);
      res.end();
    }
  });
}
route();

module.exports = subjectsRouter;