update
This commit is contained in:
@@ -10,27 +10,27 @@ import { tableDefinitions } from './schema.registry';
|
|||||||
|
|
||||||
// --- Revert to original path and filename ---
|
// --- Revert to original path and filename ---
|
||||||
// 使用 process.cwd() 获取项目根目录,然后拼接路径,确保路径一致性
|
// 使用 process.cwd() 获取项目根目录,然后拼接路径,确保路径一致性
|
||||||
console.log('[Connection CWD]', process.cwd()); // 添加 CWD 日志
|
// console.log('[Connection CWD]', process.cwd()); // 移除调试日志
|
||||||
const dbDir = path.join(process.cwd(), 'data'); // Correct path relative to CWD (packages/backend)
|
const dbDir = path.join(process.cwd(), 'data'); // Correct path relative to CWD (packages/backend)
|
||||||
const dbFilename = 'nexus-terminal.db'; // Revert to original filename
|
const dbFilename = 'nexus-terminal.db'; // Revert to original filename
|
||||||
const dbPath = path.join(dbDir, dbFilename);
|
const dbPath = path.join(dbDir, dbFilename);
|
||||||
console.log(`[DB Path] Determined database directory: ${dbDir}`);
|
// console.log(`[DB Path] Determined database directory: ${dbDir}`); // 移除调试日志
|
||||||
console.log(`[DB Path] Determined database file path: ${dbPath}`);
|
// console.log(`[DB Path] Determined database file path: ${dbPath}`); // 移除调试日志
|
||||||
|
|
||||||
// Add logging before checking/creating directory
|
// Add logging before checking/creating directory
|
||||||
console.log(`[DB FS] Checking existence of directory: ${dbDir}`);
|
// console.log(`[DB FS] Checking existence of directory: ${dbDir}`); // 移除调试日志
|
||||||
if (!fs.existsSync(dbDir)) {
|
if (!fs.existsSync(dbDir)) {
|
||||||
console.log(`[DB FS] Directory does not exist. Attempting to create: ${dbDir}`);
|
// console.log(`[DB FS] Directory does not exist. Attempting to create: ${dbDir}`); // 移除调试日志
|
||||||
try {
|
try {
|
||||||
fs.mkdirSync(dbDir, { recursive: true });
|
fs.mkdirSync(dbDir, { recursive: true });
|
||||||
console.log(`[DB FS] Directory successfully created: ${dbDir}`);
|
// console.log(`[DB FS] Directory successfully created: ${dbDir}`); // 移除调试日志
|
||||||
} catch (mkdirErr: any) {
|
} catch (mkdirErr: any) {
|
||||||
console.error(`[DB FS] Failed to create directory ${dbDir}:`, mkdirErr.message);
|
console.error(`[DB FS] Failed to create directory ${dbDir}:`, mkdirErr.message);
|
||||||
// Consider throwing error here to prevent proceeding if directory creation fails
|
// Consider throwing error here to prevent proceeding if directory creation fails
|
||||||
throw new Error(`Failed to create database directory: ${mkdirErr.message}`);
|
throw new Error(`Failed to create database directory: ${mkdirErr.message}`);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
console.log(`[DB FS] Directory already exists: ${dbDir}`);
|
// console.log(`[DB FS] Directory already exists: ${dbDir}`); // 移除调试日志
|
||||||
}
|
}
|
||||||
|
|
||||||
const verboseSqlite3 = sqlite3.verbose();
|
const verboseSqlite3 = sqlite3.verbose();
|
||||||
@@ -99,17 +99,17 @@ export const allDb = <T = any>(db: sqlite3.Database, sql: string, params: any[]
|
|||||||
* @param db The database instance
|
* @param db The database instance
|
||||||
*/
|
*/
|
||||||
const runDatabaseInitializations = async (db: sqlite3.Database): Promise<void> => {
|
const runDatabaseInitializations = async (db: sqlite3.Database): Promise<void> => {
|
||||||
console.log('[DB Init] 开始数据库初始化序列...');
|
// console.log('[DB Init] 开始数据库初始化序列...'); // 移除调试日志
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 1. Enable foreign key constraints
|
// 1. Enable foreign key constraints
|
||||||
await runDb(db, 'PRAGMA foreign_keys = ON;'); // Use promisified runDb
|
await runDb(db, 'PRAGMA foreign_keys = ON;'); // Use promisified runDb
|
||||||
console.log('[DB Init] 外键约束已启用。');
|
// console.log('[DB Init] 外键约束已启用。'); // 移除调试日志
|
||||||
|
|
||||||
// 2. Create tables and run initializations based on the registry
|
// 2. Create tables and run initializations based on the registry
|
||||||
for (const tableDef of tableDefinitions) {
|
for (const tableDef of tableDefinitions) {
|
||||||
await runDb(db, tableDef.sql); // Create table (IF NOT EXISTS)
|
await runDb(db, tableDef.sql); // Create table (IF NOT EXISTS)
|
||||||
console.log(`[DB Init] ${tableDef.name} 表已存在或已创建。`);
|
// console.log(`[DB Init] ${tableDef.name} 表已存在或已创建。`); // 移除调试日志
|
||||||
if (tableDef.init) {
|
if (tableDef.init) {
|
||||||
// Pass the db instance to the init function
|
// Pass the db instance to the init function
|
||||||
await tableDef.init(db);
|
await tableDef.init(db);
|
||||||
@@ -121,7 +121,7 @@ const runDatabaseInitializations = async (db: sqlite3.Database): Promise<void> =
|
|||||||
// await runMigrations(db);
|
// await runMigrations(db);
|
||||||
// console.log('[DB Init] 迁移检查完成。');
|
// console.log('[DB Init] 迁移检查完成。');
|
||||||
|
|
||||||
console.log('[DB Init] 数据库初始化序列成功完成。');
|
// console.log('[DB Init] 数据库初始化序列成功完成。'); // 移除调试日志
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('[DB Init] 数据库初始化序列失败:', error);
|
console.error('[DB Init] 数据库初始化序列失败:', error);
|
||||||
@@ -141,7 +141,7 @@ export const getDbInstance = (): Promise<sqlite3.Database> => {
|
|||||||
// Remove connectionFailed flag and double check logic
|
// Remove connectionFailed flag and double check logic
|
||||||
|
|
||||||
// Add logging before attempting connection
|
// Add logging before attempting connection
|
||||||
console.log(`[DB Connection] Attempting to connect/open database file with explicit create flag: ${dbPath}`);
|
// console.log(`[DB Connection] Attempting to connect/open database file with explicit create flag: ${dbPath}`); // 移除调试日志
|
||||||
// Explicitly add OPEN_READWRITE and OPEN_CREATE flags
|
// Explicitly add OPEN_READWRITE and OPEN_CREATE flags
|
||||||
const db = new verboseSqlite3.Database(dbPath, sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, async (err) => { // Mark callback as async
|
const db = new verboseSqlite3.Database(dbPath, sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, async (err) => { // Mark callback as async
|
||||||
// --- Strict Error Check FIRST ---
|
// --- Strict Error Check FIRST ---
|
||||||
@@ -157,11 +157,11 @@ export const getDbInstance = (): Promise<sqlite3.Database> => {
|
|||||||
// Remove Double Check Flag logic
|
// Remove Double Check Flag logic
|
||||||
|
|
||||||
// If no error, proceed with success logging and initialization
|
// If no error, proceed with success logging and initialization
|
||||||
console.log(`[DB Connection] Successfully connected to SQLite database: ${dbPath}`);
|
// console.log(`[DB Connection] Successfully connected to SQLite database: ${dbPath}`); // 移除调试日志
|
||||||
try {
|
try {
|
||||||
// Wait for initializations to complete
|
// Wait for initializations to complete
|
||||||
await runDatabaseInitializations(db);
|
await runDatabaseInitializations(db);
|
||||||
console.log('[DB] Database initialization complete. Ready.');
|
// console.log('[DB] Database initialization complete. Ready.'); // 移除调试日志
|
||||||
resolve(db); // Resolve the main promise with the db instance
|
resolve(db); // Resolve the main promise with the db instance
|
||||||
} catch (initError) {
|
} catch (initError) {
|
||||||
console.error('[DB] Initialization failed after connection, closing connection...');
|
console.error('[DB] Initialization failed after connection, closing connection...');
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ app.set('trust proxy', true);
|
|||||||
// --- 会话存储设置 ---
|
// --- 会话存储设置 ---
|
||||||
// const SQLiteStore = connectSqlite3(session); // 移除旧的 Store 初始化
|
// const SQLiteStore = connectSqlite3(session); // 移除旧的 Store 初始化
|
||||||
// 使用 process.cwd() 获取项目根目录,然后拼接路径,确保路径一致性
|
// 使用 process.cwd() 获取项目根目录,然后拼接路径,确保路径一致性
|
||||||
console.log('[Index CWD 1]', process.cwd()); // 添加 CWD 日志
|
// console.log('[Index CWD 1]', process.cwd()); // 移除调试日志
|
||||||
const dbPath = path.join(process.cwd(), 'data'); // Correct path relative to CWD (packages/backend)
|
const dbPath = path.join(process.cwd(), 'data'); // Correct path relative to CWD (packages/backend)
|
||||||
|
|
||||||
// --- 中间件 ---
|
// --- 中间件 ---
|
||||||
@@ -63,7 +63,7 @@ if (sessionSecret === 'a-very-insecure-secret-for-dev') {
|
|||||||
// 提供上传的背景图片等静态资源
|
// 提供上传的背景图片等静态资源
|
||||||
const uploadsPath = path.join(__dirname, '../uploads'); // 指向 backend/uploads 目录
|
const uploadsPath = path.join(__dirname, '../uploads'); // 指向 backend/uploads 目录
|
||||||
app.use('/uploads', express.static(uploadsPath));
|
app.use('/uploads', express.static(uploadsPath));
|
||||||
console.log(`静态文件服务已启动,路径: ${uploadsPath}`);
|
// console.log(`静态文件服务已启动,路径: ${uploadsPath}`); // 移除调试日志
|
||||||
// --- 结束静态文件服务 ---
|
// --- 结束静态文件服务 ---
|
||||||
|
|
||||||
|
|
||||||
@@ -85,7 +85,7 @@ const initializeDatabase = async () => {
|
|||||||
try {
|
try {
|
||||||
// getDb() now returns a Promise and handles initialization internally
|
// getDb() now returns a Promise and handles initialization internally
|
||||||
const db = await getDbInstance(); // Correctly await the Promise, use getDbInstance
|
const db = await getDbInstance(); // Correctly await the Promise, use getDbInstance
|
||||||
console.log('数据库实例已获取并初始化完成。');
|
// console.log('数据库实例已获取并初始化完成。'); // 移除调试日志
|
||||||
|
|
||||||
// runMigrations is now just a placeholder and initialization is done within getDb
|
// runMigrations is now just a placeholder and initialization is done within getDb
|
||||||
// await runMigrations(db); // Removed call to placeholder runMigrations
|
// await runMigrations(db); // Removed call to placeholder runMigrations
|
||||||
@@ -104,9 +104,9 @@ const initializeDatabase = async () => {
|
|||||||
|
|
||||||
// 检查用户数量后不再执行任何操作 (移除了自动创建和日志记录)
|
// 检查用户数量后不再执行任何操作 (移除了自动创建和日志记录)
|
||||||
|
|
||||||
console.log(`数据库中找到 ${userCount} 个用户。`); // Log user count
|
// console.log(`数据库中找到 ${userCount} 个用户。`); // 移除调试日志
|
||||||
|
|
||||||
console.log('数据库初始化后检查完成。');
|
// console.log('数据库初始化后检查完成。'); // 移除调试日志
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('数据库初始化或检查失败:', error); // More specific error message
|
console.error('数据库初始化或检查失败:', error); // More specific error message
|
||||||
process.exit(1); // 如果数据库初始化失败,则退出进程
|
process.exit(1); // 如果数据库初始化失败,则退出进程
|
||||||
@@ -116,23 +116,23 @@ const initializeDatabase = async () => {
|
|||||||
// 启动 HTTP 服务器 (而不是直接 app.listen)
|
// 启动 HTTP 服务器 (而不是直接 app.listen)
|
||||||
const startServer = () => {
|
const startServer = () => {
|
||||||
// !! 在服务器启动前,但在数据库初始化后,设置会话中间件 !!
|
// !! 在服务器启动前,但在数据库初始化后,设置会话中间件 !!
|
||||||
console.log('数据库初始化成功,现在设置会话存储...');
|
// console.log('数据库初始化成功,现在设置会话存储...'); // 移除调试日志
|
||||||
const FileStore = sessionFileStore(session); // 使用新的 FileStore
|
const FileStore = sessionFileStore(session); // 使用新的 FileStore
|
||||||
// 使用 process.cwd() 获取项目根目录,然后拼接路径,确保路径一致性
|
// 使用 process.cwd() 获取项目根目录,然后拼接路径,确保路径一致性
|
||||||
console.log('[Index CWD 2]', process.cwd()); // 添加 CWD 日志
|
// console.log('[Index CWD 2]', process.cwd()); // 移除调试日志
|
||||||
const dataPath = path.join(process.cwd(), 'data'); // 数据库文件目录保持不变 (重命名变量以便区分)
|
const dataPath = path.join(process.cwd(), 'data'); // 数据库文件目录保持不变 (重命名变量以便区分)
|
||||||
const sessionsPath = path.join(process.cwd(), 'sessions'); // 新建 sessions 目录存储会话文件
|
const sessionsPath = path.join(process.cwd(), 'sessions'); // 新建 sessions 目录存储会话文件
|
||||||
// 确保 sessions 目录存在
|
// 确保 sessions 目录存在
|
||||||
if (!fs.existsSync(sessionsPath)) {
|
if (!fs.existsSync(sessionsPath)) {
|
||||||
fs.mkdirSync(sessionsPath, { recursive: true });
|
fs.mkdirSync(sessionsPath, { recursive: true });
|
||||||
console.log(`[Session Store] 已创建会话目录: ${sessionsPath}`);
|
// console.log(`[Session Store] 已创建会话目录: ${sessionsPath}`); // 移除调试日志
|
||||||
}
|
}
|
||||||
console.log(`[Session Store] 使用文件存储,路径: ${sessionsPath}`);
|
// console.log(`[Session Store] 使用文件存储,路径: ${sessionsPath}`); // 移除调试日志
|
||||||
const sessionMiddleware = session({
|
const sessionMiddleware = session({
|
||||||
store: new FileStore({
|
store: new FileStore({
|
||||||
path: sessionsPath, // 指定会话文件存储目录
|
path: sessionsPath, // 指定会话文件存储目录
|
||||||
ttl: 60 * 60 * 24 * 7, // 会话有效期 (秒),7天,匹配 cookie maxAge (需要秒)
|
ttl: 60 * 60 * 24 * 7, // 会话有效期 (秒),7天,匹配 cookie maxAge (需要秒)
|
||||||
logFn: (message) => { console.log('[SessionFileStore]', message); } // 可选:启用日志
|
// logFn: (message) => { console.log('[SessionFileStore]', message); } // 移除调试日志
|
||||||
// reapInterval: 3600 // 清理过期会话间隔 (秒),默认1小时
|
// reapInterval: 3600 // 清理过期会话间隔 (秒),默认1小时
|
||||||
}),
|
}),
|
||||||
secret: sessionSecret,
|
secret: sessionSecret,
|
||||||
@@ -145,10 +145,10 @@ const startServer = () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
app.use(sessionMiddleware); // 在这里应用会话中间件
|
app.use(sessionMiddleware); // 在这里应用会话中间件
|
||||||
console.log('会话中间件已应用。');
|
// console.log('会话中间件已应用。'); // 移除调试日志
|
||||||
|
|
||||||
// --- 应用 API 路由 ---
|
// --- 应用 API 路由 ---
|
||||||
console.log('应用 API 路由...');
|
// console.log('应用 API 路由...'); // 移除调试日志
|
||||||
app.use('/api/v1/auth', authRouter);
|
app.use('/api/v1/auth', authRouter);
|
||||||
app.use('/api/v1/connections', connectionsRouter);
|
app.use('/api/v1/connections', connectionsRouter);
|
||||||
app.use('/api/v1/sftp', sftpRouter);
|
app.use('/api/v1/sftp', sftpRouter);
|
||||||
@@ -166,7 +166,7 @@ const startServer = () => {
|
|||||||
app.get('/api/v1/status', (req: Request, res: Response) => {
|
app.get('/api/v1/status', (req: Request, res: Response) => {
|
||||||
res.json({ status: '后端服务运行中!' });
|
res.json({ status: '后端服务运行中!' });
|
||||||
});
|
});
|
||||||
console.log('API 路由已应用。');
|
// console.log('API 路由已应用。'); // 移除调试日志
|
||||||
|
|
||||||
|
|
||||||
server.listen(port, () => { // 使用 server.listen
|
server.listen(port, () => { // 使用 server.listen
|
||||||
|
|||||||
Reference in New Issue
Block a user