first
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
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()) {
|
||||
const data = await file.json();
|
||||
return ctx.json(data);
|
||||
}
|
||||
|
||||
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()) {
|
||||
const data = await file.json();
|
||||
return ctx.json(data);
|
||||
}
|
||||
|
||||
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()) {
|
||||
existing = await file.json();
|
||||
}
|
||||
|
||||
const merged = { ...existing, ...body };
|
||||
await ensureDir(filePath);
|
||||
await Bun.write(filePath, JSON.stringify(merged, null, 2));
|
||||
return ctx.json(merged);
|
||||
});
|
||||
Reference in New Issue
Block a user