89 lines
2.4 KiB
TypeScript
89 lines
2.4 KiB
TypeScript
import { createRouter } from '../../create-router';
|
|
import { mkdir } from 'node:fs/promises';
|
|
import { dirname } from 'node:path';
|
|
import { getUserSettingsFile, getUserStateFile } from '@@/data-path';
|
|
|
|
const DEFAULT_SETTINGS = {
|
|
chat: {
|
|
defaultProvider: 'claude',
|
|
defaultModel: null,
|
|
systemPrompt: '',
|
|
temperature: 1,
|
|
defaultPwd: '~',
|
|
},
|
|
appearance: {
|
|
theme: 'light',
|
|
},
|
|
};
|
|
|
|
const ensureDir = (filePath: string) => mkdir(dirname(filePath), { recursive: true });
|
|
|
|
export const settingsRouter = createRouter();
|
|
|
|
// GET /settings — return settings.json, auto-create with defaults if missing
|
|
settingsRouter.get('/settings', async (ctx) => {
|
|
const email = ctx.get('user').email;
|
|
const filePath = getUserSettingsFile(email);
|
|
const file = Bun.file(filePath);
|
|
|
|
if (await file.exists()) {
|
|
try {
|
|
return ctx.json(await file.json());
|
|
} catch {
|
|
// corrupted — fall through to defaults
|
|
}
|
|
}
|
|
|
|
await ensureDir(filePath);
|
|
await Bun.write(file, JSON.stringify(DEFAULT_SETTINGS, null, 2));
|
|
return ctx.json(DEFAULT_SETTINGS);
|
|
});
|
|
|
|
// PUT /settings — full replacement
|
|
settingsRouter.put('/settings', async (ctx) => {
|
|
const email = ctx.get('user').email;
|
|
const body = ctx.get('body');
|
|
const filePath = getUserSettingsFile(email);
|
|
|
|
await ensureDir(filePath);
|
|
await Bun.write(filePath, JSON.stringify(body, null, 2));
|
|
return ctx.json(body);
|
|
});
|
|
|
|
// GET /state — return state.json, auto-create with {} if missing
|
|
settingsRouter.get('/state', async (ctx) => {
|
|
const email = ctx.get('user').email;
|
|
const filePath = getUserStateFile(email);
|
|
const file = Bun.file(filePath);
|
|
|
|
if (await file.exists()) {
|
|
try {
|
|
return ctx.json(await file.json());
|
|
} catch {
|
|
// corrupted — fall through to empty
|
|
}
|
|
}
|
|
|
|
await ensureDir(filePath);
|
|
await Bun.write(file, JSON.stringify({}, null, 2));
|
|
return ctx.json({});
|
|
});
|
|
|
|
// PATCH /state — shallow-merge incoming keys
|
|
settingsRouter.patch('/state', async (ctx) => {
|
|
const email = ctx.get('user').email;
|
|
const body = ctx.get('body');
|
|
const filePath = getUserStateFile(email);
|
|
const file = Bun.file(filePath);
|
|
|
|
let existing: Record<string, unknown> = {};
|
|
if (await file.exists()) {
|
|
try { existing = await file.json(); } catch { /* corrupted — start fresh */ }
|
|
}
|
|
|
|
const merged = { ...existing, ...body };
|
|
await ensureDir(filePath);
|
|
await Bun.write(filePath, JSON.stringify(merged, null, 2));
|
|
return ctx.json(merged);
|
|
});
|