-
Notifications
You must be signed in to change notification settings - Fork 11
/
exam-dao.js
103 lines (93 loc) · 2.48 KB
/
exam-dao.js
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
'use strict';
/* Data Access Object (DAO) module for accessing courses and exams */
const db = require('./db');
// get all courses
exports.listCourses = () => {
return new Promise((resolve, reject) => {
const sql = 'SELECT * FROM course';
db.all(sql, [], (err, rows) => {
if (err) {
reject(err);
return;
}
const courses = rows.map((e) => ({ code: e.code, name: e.name, CFU: e.CFU }));
resolve(courses);
});
});
};
// get the course identified by {code}
exports.getCourse = (code) => {
return new Promise((resolve, reject) => {
const sql = 'SELECT * FROM course WHERE code = ?';
db.get(sql, [code], (err, row) => {
if (err) {
reject(err);
return;
}
if (row == undefined) {
resolve({error: 'Course not found.'});
} else {
const course = { code: row.code, name: row.name, CFU: row.CFU };
resolve(course);
}
});
});
};
// get all exams
exports.listExams = (userId) => {
return new Promise((resolve, reject) => {
const sql = 'SELECT coursecode, score, date FROM exam WHERE userid = ?';
db.all(sql, [userId], (err, rows) => {
if (err) {
reject(err);
return;
}
const exams = rows.map((e) => (
{
code: e.coursecode,
score: e.score,
date: e.date,
}));
resolve(exams);
});
});
};
// add a new exam
exports.createExam = (exam, userId) => {
return new Promise((resolve, reject) => {
const sql = 'INSERT INTO exam(coursecode, date, score, userid) VALUES(?, DATE(?), ?, ?)';
db.run(sql, [exam.code, exam.date, exam.score, userId], function (err) {
if (err) {
reject(err);
return;
}
resolve(this.lastID);
});
});
};
// update an existing exam
exports.updateExam = (exam, userId) => {
return new Promise((resolve, reject) => {
const sql = 'UPDATE exam SET date=DATE(?), score=? WHERE coursecode = ? AND userid = ?';
db.run(sql, [exam.date, exam.score, exam.code, userId], function (err) {
if (err) {
reject(err);
return;
}
resolve(this.lastID);
});
});
};
// delete an existing exam
exports.deleteExam = (courseCode, userId) => {
return new Promise((resolve, reject) => {
const sql = 'DELETE FROM exam WHERE coursecode = ? AND userid = ?';
db.run(sql, [courseCode, userId], (err) => {
if (err) {
reject(err);
return;
} else
resolve(null);
});
});
}