67 lines
2.3 KiB
JavaScript
67 lines
2.3 KiB
JavaScript
const express = require('express');
|
|
|
|
function createConfigRoutes(db) {
|
|
const router = express.Router();
|
|
|
|
// Get all configs (optionally by category)
|
|
router.get('/', (req, res) => {
|
|
const { category } = req.query;
|
|
let configs;
|
|
if (category) {
|
|
configs = db.prepare('SELECT * FROM configs WHERE category = ? ORDER BY key').all(category);
|
|
} else {
|
|
configs = db.prepare('SELECT * FROM configs ORDER BY category, key').all();
|
|
}
|
|
// Group by category
|
|
const grouped = {};
|
|
for (const c of configs) {
|
|
if (!grouped[c.category]) grouped[c.category] = {};
|
|
grouped[c.category][c.key] = c.value;
|
|
}
|
|
res.json(grouped);
|
|
});
|
|
|
|
// Get single config
|
|
router.get('/:key', (req, res) => {
|
|
const config = db.prepare('SELECT * FROM configs WHERE key = ?').get(req.params.key);
|
|
if (!config) return res.status(404).json({ error: 'Config not found' });
|
|
res.json(config);
|
|
});
|
|
|
|
// Update config
|
|
router.put('/:key', (req, res) => {
|
|
const { value } = req.body;
|
|
if (value === undefined) return res.status(400).json({ error: 'value is required' });
|
|
const existing = db.prepare('SELECT * FROM configs WHERE key = ?').get(req.params.key);
|
|
if (existing) {
|
|
db.prepare('UPDATE configs SET value = ?, updated_at = CURRENT_TIMESTAMP WHERE key = ?').run(value, req.params.key);
|
|
} else {
|
|
const { category } = req.body;
|
|
db.prepare('INSERT INTO configs (key, value, category) VALUES (?, ?, ?)').run(req.params.key, value, category || 'general');
|
|
}
|
|
res.json(db.prepare('SELECT * FROM configs WHERE key = ?').get(req.params.key));
|
|
});
|
|
|
|
// Batch update configs
|
|
router.put('/', (req, res) => {
|
|
const { configs } = req.body;
|
|
if (!configs || typeof configs !== 'object') {
|
|
return res.status(400).json({ error: 'configs object required' });
|
|
}
|
|
const upsert = db.prepare(
|
|
'INSERT INTO configs (key, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP) ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=CURRENT_TIMESTAMP'
|
|
);
|
|
const batch = db.transaction(() => {
|
|
for (const [key, value] of Object.entries(configs)) {
|
|
upsert.run(key, String(value));
|
|
}
|
|
});
|
|
batch();
|
|
res.json({ success: true });
|
|
});
|
|
|
|
return router;
|
|
}
|
|
|
|
module.exports = createConfigRoutes;
|