更新安全配置项目

This commit is contained in:
2026-04-18 23:52:15 +08:00
parent 70d3020035
commit 59b3117eb9
7 changed files with 332 additions and 377 deletions
+55 -55
View File
@@ -1,68 +1,68 @@
import { NextRequest, NextResponse } from "next/server"; import {NextRequest, NextResponse} from "next/server";
import { batchTranslateWithAI, translateWithAI } from "@/lib/ai-translate"; import {batchTranslateWithAI, translateWithAI} from "@/lib/ai-translate";
// 单个翻译 // 单个翻译
export async function GET(request: NextRequest) { export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url); const {searchParams} = new URL(request.url);
const word = searchParams.get("word"); const word = searchParams.get("word");
if (!word) { if (!word) {
return NextResponse.json({ error: "缺少 word 参数" }, { status: 400 }); return NextResponse.json({error: "缺少 word 参数"}, {status: 400});
}
try {
const translation = await translateWithAI(word);
if (!translation) {
return NextResponse.json({ error: "翻译失败" }, { status: 500 });
} }
return NextResponse.json({ try {
word, const translation = await translateWithAI(word);
english: translation,
}); if (!translation) {
} catch (error) { return NextResponse.json({error: "翻译失败"}, {status: 500});
console.error("AI translation error:", error); }
return NextResponse.json(
{ error: String(error) }, return NextResponse.json({
{ status: 500 } word,
); english: translation,
} });
} catch (error) {
console.error("AI translation error:", error);
return NextResponse.json(
{error: String(error)},
{status: 500}
);
}
} }
// 批量翻译 // 批量翻译
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
try { try {
const body = await request.json(); const body = await request.json();
const { words } = body as { words: string[] }; const {words} = body as { words: string[] };
if (!Array.isArray(words) || words.length === 0) { if (!Array.isArray(words) || words.length === 0) {
return NextResponse.json({ error: "缺少 words 参数(数组)" }, { status: 400 }); return NextResponse.json({error: "缺少 words 参数(数组)"}, {status: 400});
}
// 检查 API Key
if (!process.env.AI_API_KEY) {
return NextResponse.json({error: "AI 配置未完成,请先在设置中配置 AI"}, {status: 500});
}
const results = await batchTranslateWithAI(words);
// 转换为响应格式
const translations: Record<string, string | null> = {};
for (const word of words) {
translations[word] = results.get(word) || null;
}
return NextResponse.json({
translations,
total: words.length,
success: results.size,
});
} catch (error) {
console.error("AI batch translation error:", error);
return NextResponse.json(
{error: String(error)},
{status: 500}
);
} }
// 检查 API Key
if (!process.env.AI_API_KEY) {
return NextResponse.json({ error: "AI 配置未完成,请先在设置中配置 AI" }, { status: 500 });
}
const results = await batchTranslateWithAI(words);
// 转换为响应格式
const translations: Record<string, string | null> = {};
for (const word of words) {
translations[word] = results.get(word) || null;
}
return NextResponse.json({
translations,
total: words.length,
success: results.size,
});
} catch (error) {
console.error("AI batch translation error:", error);
return NextResponse.json(
{ error: String(error) },
{ status: 500 }
);
}
} }
+35 -35
View File
@@ -1,48 +1,48 @@
import { NextRequest, NextResponse } from "next/server"; import {NextRequest, NextResponse} from "next/server";
import { getTranslation, getTranslations } from "@/lib/database"; import {getTranslation, getTranslations} from "@/lib/database";
// 单个翻译查询 // 单个翻译查询
export async function GET(request: NextRequest) { export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url); const {searchParams} = new URL(request.url);
const chineseName = searchParams.get("name"); const chineseName = searchParams.get("name");
if (!chineseName) { if (!chineseName) {
return NextResponse.json({ error: "缺少 name 参数" }, { status: 400 }); return NextResponse.json({error: "缺少 name 参数"}, {status: 400});
} }
const translation = await getTranslation(chineseName); const translation = await getTranslation(chineseName);
return NextResponse.json({ return NextResponse.json({
chinese: chineseName, chinese: chineseName,
english: translation, english: translation,
found: translation !== null, found: translation !== null,
}); });
} }
// 批量翻译查询 // 批量翻译查询
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
try { try {
const body = await request.json(); const body = await request.json();
const { names } = body as { names: string[] }; const {names} = body as { names: string[] };
if (!names || !Array.isArray(names)) { if (!names || !Array.isArray(names)) {
return NextResponse.json({ error: "缺少 names 参数(数组)" }, { status: 400 }); return NextResponse.json({error: "缺少 names 参数(数组)"}, {status: 400});
}
const translations = await getTranslations(names);
const result: Record<string, string | null> = {};
for (const name of names) {
result[name] = translations.get(name) || null;
}
return NextResponse.json({
translations: result,
total: names.length,
found: translations.size,
});
} catch (error) {
console.error("Translation API error:", error);
return NextResponse.json({error: "请求格式错误"}, {status: 400});
} }
const translations = await getTranslations(names);
const result: Record<string, string | null> = {};
for (const name of names) {
result[name] = translations.get(name) || null;
}
return NextResponse.json({
translations: result,
total: names.length,
found: translations.size,
});
} catch (error) {
console.error("Translation API error:", error);
return NextResponse.json({ error: "请求格式错误" }, { status: 400 });
}
} }
+52 -105
View File
@@ -1,34 +1,35 @@
"use client"; "use client";
import {useState, useCallback, useEffect} from "react"; import {useCallback, useEffect, useState} from "react";
import { import {
Upload, AlertCircle,
Sun,
Apple, Apple,
UtensilsCrossed, CheckCircle2,
Cookie, Cookie,
Download,
Heart, Heart,
Languages, Languages,
CheckCircle2,
Loader2, Loader2,
Settings,
Sun,
Upload,
UtensilsCrossed,
X, X,
AlertCircle,
Download, Settings,
} from "lucide-react"; } from "lucide-react";
import Link from 'next/link' import Link from 'next/link'
import {Button} from "@/components/ui/button"; import {Button} from "@/components/ui/button";
import { import {
AlignmentType,
Document, Document,
Packer, Packer,
Table,
TableRow,
TableCell,
TextRun,
Paragraph,
AlignmentType,
WidthType,
PageOrientation, PageOrientation,
TableLayoutType Paragraph,
Table,
TableCell,
TableLayoutType,
TableRow,
TextRun,
WidthType
} from "docx"; } from "docx";
// 餐食类型 // 餐食类型
@@ -228,7 +229,7 @@ export default function RecipeTranslationPage() {
orientation: "landscape", orientation: "landscape",
secondPageHeader: false, secondPageHeader: false,
}; };
const { untranslatedColor, orientation, secondPageHeader } = exportConfig; const {untranslatedColor, orientation, secondPageHeader} = exportConfig;
// 2. 收集所有需要翻译的内容(星期、餐食类型、菜品) // 2. 收集所有需要翻译的内容(星期、餐食类型、菜品)
const allNames: string[] = []; const allNames: string[] = [];
@@ -374,101 +375,47 @@ export default function RecipeTranslationPage() {
}) })
); );
} }
return new TableRow({children: headerCells, tableHeader: true}); return new TableRow({ children: headerCells, tableHeader: false });
}; };
// 估算每页能放多少天(横向 A4 约 27cm 高度,减去标题和边距约 25cm,每行约 1cm)
const daysPerPage = 5;
// 构建 sections // 构建 sections
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const sections: any[] = []; const sections: any[] = [];
if (secondPageHeader && dayRows.length > daysPerPage) { sections.push({
// 分页模式:每页有表头 properties: {
const pageCount = Math.ceil(dayRows.length / daysPerPage); page: {
size: {
for (let page = 0; page < pageCount; page++) { orientation: isLandscape ? PageOrientation.LANDSCAPE : PageOrientation.PORTRAIT,
const startIdx = page * daysPerPage; width: pageWidth,
const endIdx = Math.min(startIdx + daysPerPage, dayRows.length); height: pageHeight,
const pageRows = dayRows.slice(startIdx, endIdx);
sections.push({
properties: {
page: {
size: {
orientation: isLandscape ? PageOrientation.LANDSCAPE : PageOrientation.PORTRAIT,
width: pageWidth,
height: pageHeight,
},
margin: {
top: 700,
bottom: 700,
left: 900,
right: 900,
},
},
}, },
children: [ margin: {
...(page === 0 ? [ top: 700,
new Paragraph({ bottom: 700,
children: [ left: 900,
new TextRun({ right: 900,
text: t(data.title?.zh || "食谱") || data.title?.zh || "食谱",
bold: true,
size: 32,
}),
],
alignment: AlignmentType.CENTER,
}),
new Paragraph({children: []}),
] : []),
new Table({
rows: [buildHeaderRow(), ...pageRows],
width: {size: 100, type: WidthType.PERCENTAGE},
layout: TableLayoutType.FIXED,
}),
],
});
}
} else {
// 普通模式:单表格无分页表头
sections.push({
properties: {
page: {
size: {
orientation: isLandscape ? PageOrientation.LANDSCAPE : PageOrientation.PORTRAIT,
width: pageWidth,
height: pageHeight,
},
margin: {
top: 700,
bottom: 700,
left: 900,
right: 900,
},
}, },
}, },
children: [ },
new Paragraph({ children: [
children: [ new Paragraph({
new TextRun({ children: [
text: t(data.title?.zh || "食谱") || data.title?.zh || "食谱", new TextRun({
bold: true, text: `${fileName || data.title?.zh || "食谱翻译"}`,
size: 32, bold: true,
}), size: 32,
], }),
alignment: AlignmentType.CENTER, ],
}), alignment: AlignmentType.CENTER,
new Paragraph({children: []}), }),
new Table({ new Paragraph({children: []}),
rows: [buildHeaderRow(), ...dayRows], new Table({
width: {size: 100, type: WidthType.PERCENTAGE}, rows: [buildHeaderRow(), ...dayRows],
layout: TableLayoutType.FIXED, width: {size: 100, type: WidthType.PERCENTAGE},
}), layout: TableLayoutType.FIXED
], }),
}); ],
} });
const doc = new Document({ const doc = new Document({
sections, sections,
@@ -755,7 +702,7 @@ export default function RecipeTranslationPage() {
key={dish.id} key={dish.id}
className="flex flex-col gap-0.5 text-sm" className="flex flex-col gap-0.5 text-sm"
> >
<span style={{ color: dish.name.en ? undefined : exportConfig.untranslatedColor }}> <span style={{color: dish.name.en ? undefined : exportConfig.untranslatedColor}}>
{dish.name.zh} {dish.name.zh}
</span> </span>
{dish.name.en && ( {dish.name.en && (
@@ -788,7 +735,7 @@ export default function RecipeTranslationPage() {
key={dish.id} key={dish.id}
className="flex flex-col gap-0.5" className="flex flex-col gap-0.5"
> >
<span style={{ color: dish.name.en ? undefined : exportConfig.untranslatedColor }}> <span style={{color: dish.name.en ? undefined : exportConfig.untranslatedColor}}>
{dish.name.zh} {dish.name.zh}
</span> </span>
{dish.name.en && ( {dish.name.en && (
+4 -24
View File
@@ -1,19 +1,17 @@
"use client"; "use client";
import { useState, useEffect } from "react"; import {useEffect, useState} from "react";
import { useToast } from "@/components/ui/toast"; import {useToast} from "@/components/ui/toast";
import { Loader2 } from "lucide-react"; import {Loader2} from "lucide-react";
import { Button } from "@/components/ui/button"; import {Button} from "@/components/ui/button";
interface ExportConfig { interface ExportConfig {
untranslatedColor: string; untranslatedColor: string;
secondPageHeader: boolean;
orientation: "portrait" | "landscape"; orientation: "portrait" | "landscape";
} }
const defaultExportConfig: ExportConfig = { const defaultExportConfig: ExportConfig = {
untranslatedColor: "CC0000", untranslatedColor: "CC0000",
secondPageHeader: false,
orientation: "landscape", orientation: "landscape",
}; };
@@ -30,7 +28,6 @@ export default function ExportPage() {
if (result.success && result.data) { if (result.success && result.data) {
setConfig({ setConfig({
untranslatedColor: result.data.export?.untranslatedColor || defaultExportConfig.untranslatedColor, untranslatedColor: result.data.export?.untranslatedColor || defaultExportConfig.untranslatedColor,
secondPageHeader: result.data.export?.secondPageHeader ?? defaultExportConfig.secondPageHeader,
orientation: result.data.export?.orientation || defaultExportConfig.orientation, orientation: result.data.export?.orientation || defaultExportConfig.orientation,
}); });
} }
@@ -136,19 +133,6 @@ export default function ExportPage() {
</label> </label>
</div> </div>
</div> </div>
<div className="space-y-2">
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={config.secondPageHeader}
onChange={(e) => setConfig({ ...config, secondPageHeader: e.target.checked })}
className="h-4 w-4 cursor-pointer rounded border-input"
/>
<span className="text-sm"></span>
</label>
<p className="text-xs text-muted-foreground"></p>
</div>
</div> </div>
{/* 预览 */} {/* 预览 */}
@@ -169,10 +153,6 @@ export default function ExportPage() {
<span className="text-sm"></span> <span className="text-sm"></span>
<span className="text-sm">{config.orientation === "landscape" ? "横向 (Landscape)" : "纵向 (Portrait)"}</span> <span className="text-sm">{config.orientation === "landscape" ? "横向 (Landscape)" : "纵向 (Portrait)"}</span>
</div> </div>
<div className="flex items-center gap-2">
<span className="text-sm"></span>
<span className="text-sm">{config.secondPageHeader ? "启用" : "禁用"}</span>
</div>
</div> </div>
</div> </div>
</div> </div>
+19
View File
@@ -0,0 +1,19 @@
{
"db": {
"host": "100.66.1.4",
"port": 3306,
"user": "root",
"password": "sc666666",
"database": "recipe_tools"
},
"ai": {
"apiKey": "6a81b361620a44fd86aa3c8fcd833800.PjPyiU8kSzCTviYa",
"baseUrl": "https://open.bigmodel.cn/api/paas/v4/",
"model": "GLM-4.7-Flash"
},
"export": {
"untranslatedColor": "#FF0000",
"secondPageHeader": false,
"orientation": "landscape"
}
}
+16 -1
View File
@@ -1,10 +1,25 @@
import { defineConfig, globalIgnores } from "eslint/config"; import {defineConfig, globalIgnores} from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals"; import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript"; import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([ const eslintConfig = defineConfig([
...nextVitals, ...nextVitals,
...nextTs, ...nextTs,
{
rules: {
// Allow any type
"@typescript-eslint/no-explicit-any": "off",
// Allow unused variables with underscore prefix
"@typescript-eslint/no-unused-vars": ["warn", { "argsIgnorePattern": "^_" }],
// Reduce required type annotations
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
// Allow console logs
"no-console": "off",
// Reduce strictness
"react-hooks/exhaustive-deps": "warn",
}
},
// Override default ignores of eslint-config-next. // Override default ignores of eslint-config-next.
globalIgnores([ globalIgnores([
// Default ignores of eslint-config-next: // Default ignores of eslint-config-next:
+147 -153
View File
@@ -2,32 +2,30 @@ import fs from "fs";
import path from "path"; import path from "path";
export interface DBConfig { export interface DBConfig {
host: string; host: string;
port: number; port: number;
user: string; user: string;
password: string; password: string;
database: string; database: string;
} }
export interface AIConfig { export interface AIConfig {
apiKey: string; apiKey: string;
baseUrl: string; baseUrl: string;
model: string; model: string;
} }
export interface ExportConfig { export interface ExportConfig {
// 未翻译文本的颜色 (hex) // 未翻译文本的颜色 (hex)
untranslatedColor: string; untranslatedColor: string;
// 第二页是否显示表头 // 页面方向: portrait | landscape
secondPageHeader: boolean; orientation: "portrait" | "landscape";
// 页面方向: portrait | landscape
orientation: "portrait" | "landscape";
} }
export interface AppConfig { export interface AppConfig {
db: DBConfig; db: DBConfig;
ai: AIConfig; ai: AIConfig;
export: ExportConfig; export: ExportConfig;
} }
// 配置文件路径(单一文件) // 配置文件路径(单一文件)
@@ -37,29 +35,29 @@ const configPath = path.join(process.cwd(), "config.json");
* 检查配置文件是否存在 * 检查配置文件是否存在
*/ */
function configFileExists(): boolean { function configFileExists(): boolean {
return fs.existsSync(configPath); return fs.existsSync(configPath);
} }
/** /**
* 读取完整配置(仅从 config.json * 读取完整配置(仅从 config.json
*/ */
function readConfigFile(): Partial<AppConfig> { function readConfigFile(): Partial<AppConfig> {
try { try {
if (configFileExists()) { if (configFileExists()) {
const content = fs.readFileSync(configPath, "utf-8"); const content = fs.readFileSync(configPath, "utf-8");
return JSON.parse(content); return JSON.parse(content);
}
} catch (e) {
console.error("Config read error:", e);
} }
} catch (e) { return {};
console.error("Config read error:", e);
}
return {};
} }
/** /**
* 写入完整配置 * 写入完整配置
*/ */
function writeConfigFile(config: AppConfig): void { function writeConfigFile(config: AppConfig): void {
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), "utf-8"); fs.writeFileSync(configPath, JSON.stringify(config, null, 2), "utf-8");
} }
/** /**
@@ -67,185 +65,181 @@ function writeConfigFile(config: AppConfig): void {
* 从环境变量读取初始值写入 config.json * 从环境变量读取初始值写入 config.json
*/ */
function initConfigFromEnv(): AppConfig { function initConfigFromEnv(): AppConfig {
const initialConfig: AppConfig = { const initialConfig: AppConfig = {
db: { db: {
host: process.env.DB_HOST || "127.0.0.1", host: process.env.DB_HOST || "127.0.0.1",
port: process.env.DB_PORT ? parseInt(process.env.DB_PORT) : 3306, port: process.env.DB_PORT ? parseInt(process.env.DB_PORT) : 3306,
user: process.env.DB_USER || "root", user: process.env.DB_USER || "root",
password: process.env.DB_PASSWORD || "", password: process.env.DB_PASSWORD || "",
database: process.env.DB_NAME || "recipe_tools", database: process.env.DB_NAME || "recipe_tools",
}, },
ai: { ai: {
apiKey: process.env.AI_API_KEY || "", apiKey: process.env.AI_API_KEY || "",
baseUrl: process.env.AI_BASE_URL || "https://api.openai.com/v1", baseUrl: process.env.AI_BASE_URL || "https://api.openai.com/v1",
model: process.env.AI_MODEL || "gpt-3.5-turbo", model: process.env.AI_MODEL || "gpt-3.5-turbo",
}, },
export: { export: {
untranslatedColor: process.env.EXPORT_UNTRANSLATED_COLOR || "CC0000", untranslatedColor: process.env.EXPORT_UNTRANSLATED_COLOR || "CC0000",
secondPageHeader: process.env.EXPORT_SECOND_PAGE_HEADER === "true", orientation: (process.env.EXPORT_ORIENTATION as "portrait" | "landscape") || "landscape",
orientation: (process.env.EXPORT_ORIENTATION as "portrait" | "landscape") || "landscape", },
}, };
};
writeConfigFile(initialConfig); writeConfigFile(initialConfig);
return initialConfig; return initialConfig;
} }
/** /**
* 获取数据库配置(仅从 config.json * 获取数据库配置(仅从 config.json
*/ */
export function getDBConfig(): DBConfig { export function getDBConfig(): DBConfig {
// 如果配置文件不存在,从环境变量初始化 // 如果配置文件不存在,从环境变量初始化
if (!configFileExists()) { if (!configFileExists()) {
return initConfigFromEnv().db; return initConfigFromEnv().db;
} }
const fileConfig = readConfigFile(); const fileConfig = readConfigFile();
const defaultConfig: DBConfig = { const defaultConfig: DBConfig = {
host: "127.0.0.1", host: "127.0.0.1",
port: 3306, port: 3306,
user: "root", user: "root",
password: "", password: "",
database: "recipe_tools", database: "recipe_tools",
};
if (fileConfig.db) {
return {
host: fileConfig.db.host || defaultConfig.host,
port: fileConfig.db.port || defaultConfig.port,
user: fileConfig.db.user || defaultConfig.user,
password: fileConfig.db.password ?? defaultConfig.password,
database: fileConfig.db.database || defaultConfig.database,
}; };
}
return defaultConfig; if (fileConfig.db) {
return {
host: fileConfig.db.host || defaultConfig.host,
port: fileConfig.db.port || defaultConfig.port,
user: fileConfig.db.user || defaultConfig.user,
password: fileConfig.db.password ?? defaultConfig.password,
database: fileConfig.db.database || defaultConfig.database,
};
}
return defaultConfig;
} }
/** /**
* 获取AI翻译配置(仅从 config.json * 获取AI翻译配置(仅从 config.json
*/ */
export function getAIConfig(): AIConfig { export function getAIConfig(): AIConfig {
// 如果配置文件不存在,从环境变量初始化 // 如果配置文件不存在,从环境变量初始化
if (!configFileExists()) { if (!configFileExists()) {
return initConfigFromEnv().ai; return initConfigFromEnv().ai;
} }
const fileConfig = readConfigFile(); const fileConfig = readConfigFile();
const defaultConfig: AIConfig = { const defaultConfig: AIConfig = {
apiKey: "", apiKey: "",
baseUrl: "https://api.openai.com/v1", baseUrl: "https://api.openai.com/v1",
model: "gpt-3.5-turbo", model: "gpt-3.5-turbo",
};
if (fileConfig.ai) {
return {
apiKey: fileConfig.ai.apiKey ?? defaultConfig.apiKey,
baseUrl: fileConfig.ai.baseUrl || defaultConfig.baseUrl,
model: fileConfig.ai.model || defaultConfig.model,
}; };
}
return defaultConfig; if (fileConfig.ai) {
return {
apiKey: fileConfig.ai.apiKey ?? defaultConfig.apiKey,
baseUrl: fileConfig.ai.baseUrl || defaultConfig.baseUrl,
model: fileConfig.ai.model || defaultConfig.model,
};
}
return defaultConfig;
} }
/** /**
* 获取导出配置(仅从 config.json * 获取导出配置(仅从 config.json
*/ */
export function getExportConfig(): ExportConfig { export function getExportConfig(): ExportConfig {
// 如果配置文件不存在,从环境变量初始化 // 如果配置文件不存在,从环境变量初始化
if (!configFileExists()) { if (!configFileExists()) {
return initConfigFromEnv().export; return initConfigFromEnv().export;
} }
const fileConfig = readConfigFile(); const fileConfig = readConfigFile();
const defaultConfig: ExportConfig = { const defaultConfig: ExportConfig = {
untranslatedColor: "CC0000", untranslatedColor: "CC0000",
secondPageHeader: false, orientation: "landscape",
orientation: "landscape",
};
if (fileConfig.export) {
return {
untranslatedColor: fileConfig.export.untranslatedColor || defaultConfig.untranslatedColor,
secondPageHeader: fileConfig.export.secondPageHeader ?? defaultConfig.secondPageHeader,
orientation: fileConfig.export.orientation || defaultConfig.orientation,
}; };
}
return defaultConfig; if (fileConfig.export) {
return {
untranslatedColor: fileConfig.export.untranslatedColor || defaultConfig.untranslatedColor,
orientation: fileConfig.export.orientation || defaultConfig.orientation,
};
}
return defaultConfig;
} }
/** /**
* 获取完整配置 * 获取完整配置
*/ */
export function getAllConfig(): AppConfig { export function getAllConfig(): AppConfig {
// 如果配置文件不存在,从环境变量初始化 // 如果配置文件不存在,从环境变量初始化
if (!configFileExists()) { if (!configFileExists()) {
return initConfigFromEnv(); return initConfigFromEnv();
} }
return { return {
db: getDBConfig(), db: getDBConfig(),
ai: getAIConfig(), ai: getAIConfig(),
export: getExportConfig(), export: getExportConfig(),
}; };
} }
/** /**
* 保存AI翻译配置 * 保存AI翻译配置
*/ */
export function saveAIConfig(config: Partial<AIConfig>): AIConfig { export function saveAIConfig(config: Partial<AIConfig>): AIConfig {
// 确保配置文件存在 // 确保配置文件存在
if (!configFileExists()) { if (!configFileExists()) {
initConfigFromEnv(); initConfigFromEnv();
} }
const current = getAIConfig(); const current = getAIConfig();
const newConfig: AIConfig = { const newConfig: AIConfig = {
apiKey: config.apiKey ?? current.apiKey, apiKey: config.apiKey ?? current.apiKey,
baseUrl: config.baseUrl ?? current.baseUrl, baseUrl: config.baseUrl ?? current.baseUrl,
model: config.model ?? current.model, model: config.model ?? current.model,
}; };
// 读取现有配置,更新 ai 部分 // 读取现有配置,更新 ai 部分
const fileConfig = readConfigFile(); const fileConfig = readConfigFile();
const updatedConfig: AppConfig = { const updatedConfig: AppConfig = {
db: fileConfig.db ?? { host: "127.0.0.1", port: 3306, user: "root", password: "", database: "recipe_tools" }, db: fileConfig.db ?? {host: "127.0.0.1", port: 3306, user: "root", password: "", database: "recipe_tools"},
export: fileConfig.export ?? { untranslatedColor: "CC0000", secondPageHeader: false, orientation: "landscape" }, export: fileConfig.export ?? {untranslatedColor: "CC0000", orientation: "landscape"},
ai: newConfig, ai: newConfig,
}; };
writeConfigFile(updatedConfig); writeConfigFile(updatedConfig);
return newConfig; return newConfig;
} }
/** /**
* 保存导出配置 * 保存导出配置
*/ */
export function saveExportConfig(config: Partial<ExportConfig>): ExportConfig { export function saveExportConfig(config: Partial<ExportConfig>): ExportConfig {
// 确保配置文件存在 // 确保配置文件存在
if (!configFileExists()) { if (!configFileExists()) {
initConfigFromEnv(); initConfigFromEnv();
} }
const current = getExportConfig(); const current = getExportConfig();
const newConfig: ExportConfig = { const newConfig: ExportConfig = {
untranslatedColor: config.untranslatedColor ?? current.untranslatedColor, untranslatedColor: config.untranslatedColor ?? current.untranslatedColor,
secondPageHeader: config.secondPageHeader ?? current.secondPageHeader, orientation: config.orientation ?? current.orientation,
orientation: config.orientation ?? current.orientation, };
};
// 读取现有配置,更新 export 部分 // 读取现有配置,更新 export 部分
const fileConfig = readConfigFile(); const fileConfig = readConfigFile();
const updatedConfig: AppConfig = { const updatedConfig: AppConfig = {
db: fileConfig.db ?? { host: "127.0.0.1", port: 3306, user: "root", password: "", database: "recipe_tools" }, db: fileConfig.db ?? {host: "127.0.0.1", port: 3306, user: "root", password: "", database: "recipe_tools"},
ai: fileConfig.ai ?? { apiKey: "", baseUrl: "https://api.openai.com/v1", model: "gpt-3.5-turbo" }, ai: fileConfig.ai ?? {apiKey: "", baseUrl: "https://api.openai.com/v1", model: "gpt-3.5-turbo"},
export: newConfig, export: newConfig,
}; };
writeConfigFile(updatedConfig); writeConfigFile(updatedConfig);
return newConfig; return newConfig;
} }