46 lines
2.0 KiB
TypeScript
46 lines
2.0 KiB
TypeScript
/**
|
||
* Settings Routes – key/value application settings
|
||
*/
|
||
import type { FastifyInstance } from 'fastify';
|
||
import type { DatabaseInterface } from '../database/DatabaseInterface.js';
|
||
import { requireAuth } from '../auth/authMiddleware.js';
|
||
import type { AuthService } from '../auth/AuthService.js';
|
||
import { validateSettingsKey, validateSettingsValue } from '../utils/validation.js';
|
||
|
||
/** Built-in default settings so the frontend never sees a 404 for known keys. */
|
||
const DEFAULT_SETTINGS: Record<string, string> = {
|
||
'cad.unit': 'mm',
|
||
'cad.gridSize': '20',
|
||
'cad.scaleFactor': '1',
|
||
};
|
||
|
||
export function registerSettingsRoutes(fastify: FastifyInstance, db: DatabaseInterface, authService: AuthService) {
|
||
// Get a single setting by key
|
||
fastify.get('/api/settings/:key', async (request, reply) => {
|
||
if (!requireAuth(request, reply, authService)) return;
|
||
const { key } = request.params as { key: string };
|
||
const keyErr = validateSettingsKey(key);
|
||
if (keyErr) return reply.code(400).send({ error: keyErr });
|
||
const setting = db.getSetting(key);
|
||
if (setting) return setting;
|
||
// Return a default value for known CAD settings instead of 404
|
||
if (DEFAULT_SETTINGS[key] !== undefined) {
|
||
return { key, value: DEFAULT_SETTINGS[key], updated_at: new Date().toISOString() };
|
||
}
|
||
return reply.code(404).send({ error: 'Setting not found' });
|
||
});
|
||
|
||
// Create or update a setting (upsert)
|
||
fastify.put('/api/settings/:key', async (request, reply) => {
|
||
if (!requireAuth(request, reply, authService)) return;
|
||
const { key } = request.params as { key: string };
|
||
const keyErr = validateSettingsKey(key);
|
||
if (keyErr) return reply.code(400).send({ error: keyErr });
|
||
const body = request.body as { value?: string };
|
||
const valueErr = validateSettingsValue(body.value);
|
||
if (valueErr) return reply.code(400).send({ error: valueErr });
|
||
db.setSetting(key, body.value as string);
|
||
return { key, value: body.value as string, updated_at: new Date().toISOString() };
|
||
});
|
||
}
|