39 lines
1.3 KiB
TypeScript
39 lines
1.3 KiB
TypeScript
import type { FastifyInstance } from 'fastify';
|
|
import db from '../db.js';
|
|
import { requireAuth } from '../auth.js';
|
|
|
|
type SettingsRow = { key: string; value: string };
|
|
|
|
function getAllSettings(): Record<string, string> {
|
|
const rows = db.prepare('SELECT key, value FROM settings').all() as SettingsRow[];
|
|
return Object.fromEntries(rows.map((r) => [r.key, r.value]));
|
|
}
|
|
|
|
export async function settingsRoutes(app: FastifyInstance) {
|
|
// Public — anyone can read settings (needed to render logo for guests)
|
|
app.get('/api/settings', async () => {
|
|
return getAllSettings();
|
|
});
|
|
|
|
// Admin — update one or more settings keys
|
|
app.put<{ Body: Record<string, string> }>(
|
|
'/api/settings',
|
|
{ preHandler: requireAuth },
|
|
async (req) => {
|
|
const allowed = new Set(['logo_url']);
|
|
const stmt = db.prepare(
|
|
'INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value'
|
|
);
|
|
for (const [key, value] of Object.entries(req.body)) {
|
|
if (!allowed.has(key)) continue;
|
|
if (value === '' || value == null) {
|
|
db.prepare('DELETE FROM settings WHERE key = ?').run(key);
|
|
} else {
|
|
stmt.run(key, String(value));
|
|
}
|
|
}
|
|
return getAllSettings();
|
|
}
|
|
);
|
|
}
|