-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheditposttag.js
More file actions
66 lines (58 loc) · 2.69 KB
/
editposttag.js
File metadata and controls
66 lines (58 loc) · 2.69 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
const express = require('express');
const router = express.Router();
const db = require('./db.js');
router.put('/', (req, res) => {
const { post_id, tags } = req.body;
if (!post_id || !Array.isArray(tags)) {
return res.status(400).send('Invalid request');
}
// Fetch existing tags
db.query('SELECT tag FROM post_tags WHERE post_id = ?', [post_id], (err, results) => {
if (err) {
console.error('Error fetching existing tags: ' + err.stack);
return res.status(500).send('Internal Server Error');
}
const existingTags = results.map(row => row.tag);
const newTagsSet = new Set(tags);
const existingTagsSet = new Set(existingTags);
const tagsToDelete = existingTags.filter(tag => !newTagsSet.has(tag));
const tagsToAdd = tags.filter(tag => !existingTagsSet.has(tag));
// Delete tags that are no longer present
if (tagsToDelete.length > 0) {
db.query('DELETE FROM post_tags WHERE post_id = ? AND tag IN (?)', [post_id, tagsToDelete], (err, results) => {
if (err) {
console.error('Error deleting tags: ' + err.stack);
return res.status(500).send('Internal Server Error');
}
// Insert new tags after deleting old ones
if (tagsToAdd.length > 0) {
const values = tagsToAdd.map(tag => [post_id, tag]);
db.query('INSERT INTO post_tags (post_id, tag) VALUES ?', [values], (err, results) => {
if (err) {
console.error('Error inserting tags: ' + err.stack);
return res.status(500).send('Internal Server Error');
}
res.status(200).send('Tags updated successfully');
});
} else {
res.status(200).send('Tags updated successfully');
}
});
} else {
// Insert new tags if no tags to delete
if (tagsToAdd.length > 0) {
const values = tagsToAdd.map(tag => [post_id, tag]);
db.query('INSERT INTO post_tags (post_id, tag) VALUES ?', [values], (err, results) => {
if (err) {
console.error('Error inserting tags: ' + err.stack);
return res.status(500).send('Internal Server Error');
}
res.status(200).send('Tags updated successfully');
});
} else {
res.status(200).send('Tags updated successfully');
}
}
});
});
module.exports = router;