Subjects.js
1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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;