Subjects.js
1.27 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
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;