-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetscrap.js
53 lines (46 loc) · 1.17 KB
/
getscrap.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
const express = require('express');
const router = express.Router();
const db = require('./db.js');
router.get('/', (req, res) => {
const { user_id, post_id } = req.query;
if (!user_id) {
return res.status(400).send('user_id is required');
}
let sql = '';
let values = [];
if (post_id) {
sql = `
SELECT CASE WHEN EXISTS (
SELECT 1
FROM scrap_posts
WHERE user_id = ? AND post_id = ?
) THEN TRUE ELSE FALSE END AS isScrapped
`;
values = [user_id, post_id];
} else {
sql = `
SELECT sp.*, p.*
FROM scrap_posts sp
JOIN posts p ON sp.post_id = p.post_id
WHERE sp.user_id = ?
`;
values = [user_id];
}
db.query(sql, values, (err, results) => {
if (err) {
console.error('Error querying database: ' + err.stack);
res.status(500).send('Internal Server Error');
return;
}
if (post_id) {
res.status(200).json({ isScrapped: results[0].isScrapped });
} else {
if (results.length === 0) {
res.status(204).send('No scraps found for this user');
} else {
res.status(200).json(results);
}
}
});
});
module.exports = router;