73 lines
2.0 KiB
TypeScript
73 lines
2.0 KiB
TypeScript
import mysql from "mysql2/promise";
|
|
import {getConfig} from "@/lib/config";
|
|
|
|
// 获取配置文件中的数据链接
|
|
const dataBaseConfig = getConfig().db
|
|
|
|
const pool = mysql.createPool({
|
|
host: dataBaseConfig.host || "127.0.0.1",
|
|
port: dataBaseConfig.port || 3306,
|
|
user: dataBaseConfig.user || "root",
|
|
password: dataBaseConfig.password || "123456",
|
|
database: dataBaseConfig.database || "recipe_tools",
|
|
waitForConnections: true,
|
|
connectionLimit: 10,
|
|
queueLimit: 0,
|
|
});
|
|
export default pool;
|
|
|
|
/**
|
|
* 根据中文菜名查询英文翻译
|
|
* @param chineseName 中文菜名
|
|
* @returns 翻译结果或 null
|
|
*/
|
|
export async function getTranslation(chineseName: string): Promise<string | null> {
|
|
try {
|
|
const [rows] = await pool.execute<mysql.RowDataPacket[]>(
|
|
"SELECT english FROM words WHERE word = ? LIMIT 1",
|
|
[chineseName]
|
|
);
|
|
|
|
if (rows.length > 0 && rows[0].english) {
|
|
return rows[0].english as string;
|
|
}
|
|
return null;
|
|
} catch (error) {
|
|
console.error("Database query error:", error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 批量查询翻译
|
|
* @param chineseNames 中文菜名数组
|
|
* @returns 翻译结果映射 { chineseName: englishName }
|
|
*/
|
|
export async function getTranslations(
|
|
chineseNames: string[]
|
|
): Promise<Map<string, string>> {
|
|
const result = new Map<string, string>();
|
|
|
|
if (chineseNames.length === 0) return result;
|
|
|
|
try {
|
|
const placeholders = chineseNames.map(() => "?").join(",");
|
|
const [rows] = await pool.execute<mysql.RowDataPacket[]>(
|
|
`SELECT word, english
|
|
FROM words
|
|
WHERE word IN (${placeholders})`,
|
|
chineseNames
|
|
);
|
|
|
|
for (const row of rows) {
|
|
if (row.word && row.english) {
|
|
result.set(row.word as string, row.english as string);
|
|
}
|
|
}
|
|
} catch (error) {
|
|
console.error("Database batch query error:", error);
|
|
}
|
|
|
|
return result;
|
|
}
|