Refactoring the backend

This commit is contained in:
jiangrui
2025-03-10 18:33:47 +08:00
parent 755a424530
commit a78ea7e5bd
36 changed files with 974 additions and 474 deletions

View File

@@ -1,136 +1,46 @@
// filepath: /d:/code/CloudDiskDown/backend/src/app.ts
import "./types/express";
import express, { Application } from "express";
import cors from "cors";
import cookieParser from "cookie-parser";
import { QueryTypes } from "sequelize";
// 路由和中间件导入
import express from "express";
import { container } from "./core/container";
import { TYPES } from "./core/types";
import { DatabaseService } from "./services/DatabaseService";
import { setupMiddlewares } from "./middleware";
import routes from "./routes/api";
import { errorHandler } from "./middleware/errorHandler";
import { authMiddleware } from "./middleware/auth";
// 数据库和服务相关
import sequelize from "./config/database";
import GlobalSetting from "./models/GlobalSetting";
import Searcher from "./services/Searcher";
// 常量配置
const PUBLIC_ROUTES = ["/user/login", "/user/register"];
const IMAGE_PATH = "tele-images";
const DEFAULT_PORT = 8009;
// 全局设置默认值
const DEFAULT_GLOBAL_SETTINGS = {
httpProxyHost: "127.0.0.1",
httpProxyPort: 7890,
isProxyEnabled: false,
CommonUserCode: 9527,
AdminUserCode: 230713,
};
import { logger } from "./utils/logger";
class App {
private app: Application;
private app = express();
private databaseService = container.get<DatabaseService>(TYPES.DatabaseService);
constructor() {
this.app = express();
this.setupMiddlewares();
this.setupRoutes();
this.setupErrorHandling();
this.setupExpress();
}
private setupMiddlewares(): void {
// CORS 配置
this.app.use(
cors({
origin: "*",
credentials: true,
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization", "Cookie"],
})
);
private setupExpress(): void {
// 设置中间件
setupMiddlewares(this.app);
this.app.use(cookieParser());
this.app.use(express.json());
// 身份验证中间件
this.app.use((req, res, next) => {
if (PUBLIC_ROUTES.includes(req.path) || req.path.includes(IMAGE_PATH)) {
return next();
}
authMiddleware(req, res, next);
});
}
private setupRoutes(): void {
// 设置路由
this.app.use("/", routes);
}
private setupErrorHandling(): void {
this.app.use(errorHandler);
}
private async initializeGlobalSettings(): Promise<void> {
try {
const settings = await GlobalSetting.findOne();
if (!settings) {
await GlobalSetting.create(DEFAULT_GLOBAL_SETTINGS);
console.log("✅ Global settings initialized with default values.");
}
await Searcher.updateAxiosInstance();
} catch (error) {
console.error("❌ Failed to initialize global settings:", error);
throw error;
}
}
private async cleanupBackupTables(): Promise<void> {
try {
// 查询所有以 '_backup' 结尾的备份表
const backupTables = await sequelize.query<{ name: string }>(
"SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%\\_backup%' ESCAPE '\\'",
{ type: QueryTypes.SELECT }
);
// 逐个删除备份表
for (const table of backupTables) {
if (table?.name) {
await sequelize.query(`DROP TABLE IF EXISTS ${table.name}`);
console.log(`✅ Cleaned up backup table: ${table.name}`);
}
}
} catch (error) {
console.error("❌ Failed to cleanup backup tables:", error);
throw error;
}
}
public async start(): Promise<void> {
try {
// 数据库初始化流程
await sequelize.query("PRAGMA foreign_keys = OFF");
console.log("📝 Foreign keys disabled for initialization...");
await this.cleanupBackupTables();
console.log("🧹 Backup tables cleaned up");
await sequelize.sync({ alter: true });
console.log("📚 Database schema synchronized");
await sequelize.query("PRAGMA foreign_keys = ON");
console.log("🔐 Foreign keys re-enabled");
// 初始化数据库
await this.databaseService.initialize();
logger.info("数据库初始化成功");
// 启动服务器
const port = process.env.PORT || DEFAULT_PORT;
this.app.listen(port, async () => {
await this.initializeGlobalSettings();
console.log(`
🚀 Server is running on port ${port}
🔧 Environment: ${process.env.NODE_ENV || "development"}
const port = process.env.PORT || 8009;
this.app.listen(port, () => {
logger.info(`
🚀 服务器启动成功
🌍 监听端口: ${port}
🔧 运行环境: ${process.env.NODE_ENV || "development"}
`);
});
} catch (error) {
console.error("❌ Failed to start server:", error);
logger.error("服务器启动失败:", error);
process.exit(1);
}
}
@@ -139,7 +49,7 @@ class App {
// 创建并启动应用
const application = new App();
application.start().catch((error) => {
console.error("❌ Application failed to start:", error);
logger.error("应用程序启动失败:", error);
process.exit(1);
});