import type { IncomingMessage, ServerResponse } from "node:http"; import { deleteWebuiConfig, getAllWebuiConfig, getWebuiConfig, readWebuiAvatarSettings, setWebuiConfig, setWebuiConfigMany, } from "../db/index.ts"; import { normalizeConfigKey, normalizeConfigValue } from "../services/avatars.ts"; import type { WebUiContext } from "../types/context.ts"; import { json, readBody } from "../http/request.ts"; export function handleWebuiConfigRoute( req: IncomingMessage, res: ServerResponse, ctx: WebUiContext, pathname: string, url: URL, ): boolean { if (req.method === "GET" && pathname === "/api/avatars") { json(res, readWebuiAvatarSettings()); return true; } if (req.method === "GET" && pathname === "/api/webui/config") { const key = url.searchParams.get("key"); if (key) { const normalized = normalizeConfigKey(key); json(res, { key: normalized, value: getWebuiConfig(normalized) }); return true; } json(res, { config: getAllWebuiConfig(), dbPath: ctx.db.dbPath }); return true; } if (req.method === "POST" && pathname === "/api/webui/config") { void readBody(req) .then(({ key, value, entries }) => { if (entries && typeof entries === "object" && !Array.isArray(entries)) { const normalized: Record = {}; for (const [rawKey, rawValue] of Object.entries(entries as Record)) { normalized[normalizeConfigKey(rawKey)] = normalizeConfigValue(rawValue); } setWebuiConfigMany(normalized); return json(res, { ok: true, config: getAllWebuiConfig() }); } if (typeof key !== "string") throw new Error("缺少配置键 key"); const normalizedKey = normalizeConfigKey(key); const normalizedValue = normalizeConfigValue(value); setWebuiConfig(normalizedKey, normalizedValue); return json(res, { ok: true, key: normalizedKey, value: normalizedValue }); }) .catch((err) => json(res, { error: err.message }, 500)); return true; } if (req.method === "POST" && pathname === "/api/webui/config/delete") { void readBody(req) .then(({ key }) => { const normalized = normalizeConfigKey(key); const deleted = deleteWebuiConfig(normalized); json(res, { ok: true, deleted, key: normalized }); }) .catch((err) => json(res, { error: err.message }, 500)); return true; } return false; }