-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread.model.js
More file actions
91 lines (77 loc) · 2.3 KB
/
Copy paththread.model.js
File metadata and controls
91 lines (77 loc) · 2.3 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
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
const sql = require('./db.js');
// constructor
const Thread = function(thread) {
this.user_id = thread.user_id;
this.title = thread.title;
this.body = thread.body;
}
Thread.create = (newThread, result) => {
sql.query("INSERT INTO threads SET ?", newThread, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
console.log("created Thread: ", { id: res.insertId, ...newThread });
result(null, { id: res.insertId, ...newThread });
});
};
Thread.getAll = result => {
sql.query("SELECT * FROM threads", (err, res) => {
if(err) {
console.log("error: ", err)
result(err, null)
return
}
console.log("threads: ", res);
result(null, res)
});
}
Thread.find = (threadId, result) => {
sql.query(`SELECT * FROM threads WHERE id = ${threadId}`, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
}
if (res.length) {
console.log("found thread: ", res[0]);
result(null, res[0]);
return;
}
});
}
Thread.update = (threadId, thread, result) => {
sql.query(
"UPDATE threads SET title = ?, body = ?, best_reply_id = ? WHERE id = ?",
[thread.title, thread.body, thread.best_reply_id, threadId],
(err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
}
if (res.affectedRows == 0) {
// not found Thread with the id
result({ kind: "not_found" }, null);
return;
}
console.log("thread: ", res);
result(null, res)
});
}
Thread.delete = (threadId, result) => {
sql.query("DELETE FROM threads WHERE id = ?", threadId, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
if (res.affectedRows == 0) {
// not found Thread with the threadId
result({ kind: "not_found" }, null);
return;
}
console.log("deleted thread with id: ", threadId);
result(null, res);
});
};
module.exports = Thread;