Implement tag management with SQLite; update save and retrieve endpoints

This commit is contained in:
2025-02-02 19:17:35 +01:00
parent c98aea1b06
commit 37a7e5e67a
4 changed files with 80 additions and 23 deletions

View File

@@ -3,10 +3,17 @@ const fs = require('fs');
const path = require('path');
const auth = require('../middleware/auth');
const logger = require('../logger');
const sqlite3 = require('sqlite3').verbose();
const router = express.Router();
const dataDir = '/data';
const db = new sqlite3.Database('/data/sessions.sqlite', (err) => {
if (err) {
console.error('Error opening database:', err);
}
});
// Ensure the /data directory exists
if (!fs.existsSync(dataDir)) {
fs.mkdirSync(dataDir, { recursive: true });
@@ -68,28 +75,31 @@ router.post('/add-task', auth, async (req, res) => {
// Endpoint to save tags
router.post('/save-tags', auth, async (req, res) => {
const { tags } = req.body;
const filePath = path.join(dataDir, 'tags.json');
try {
await fs.promises.writeFile(filePath, JSON.stringify(tags));
res.send({ message: 'Tags saved successfully!' });
logger.info(`New tags saved: ${tags}`);
} catch (err) {
logger.error('Error saving tags:', err);
res.status(500).send('Error saving tags.');
}
const placeholders = tags.map(() => '(?)').join(',');
const sql = `INSERT OR IGNORE INTO tags (tag) VALUES ${placeholders}`;
db.run(sql, tags, function(err) {
if (err) {
logger.error('Error saving tags:', err);
res.status(500).send('Error saving tags.');
} else {
res.send({ message: 'Tags saved successfully!' });
logger.info(`New tags saved: ${tags}`);
}
});
});
// Endpoint to retrieve tags
router.get('/get-tags', auth, async (req, res) => {
const filePath = path.join(dataDir, 'tags.json');
try {
const data = await fs.promises.readFile(filePath, 'utf-8');
const tags = JSON.parse(data);
res.json(tags);
} catch (err) {
logger.error('Error retrieving tags:', err);
res.status(500).json({ error: 'Error retrieving tags' });
}
db.all('SELECT tag FROM tags', [], (err, rows) => {
if (err) {
logger.error('Error retrieving tags:', err);
res.status(500).json({ error: 'Error retrieving tags' });
} else {
const tags = rows.map(row => row.tag);
res.json(tags);
}
});
});
module.exports = router;