From 65bd6a7759a9fcf93a19f7e5cbafadff98a74434 Mon Sep 17 00:00:00 2001 From: patdelphi Date: Fri, 22 Aug 2025 17:09:18 +0800 Subject: [PATCH] fix: Improve database persistence in Koyeb deployment - Remove forced database initialization from Dockerfile CMD - App now auto-initializes database on startup without data loss - Skip sample data creation in production environment - Ensure admin user exists in production without recreating - Fixes database reset issue on every Koyeb deployment - Maintains data persistence with proper volume mounting --- Dockerfile | 4 ++-- server/index.cjs | 25 +++++++++++++++++++++++++ server/scripts/initDatabase.cjs | 8 ++++++-- 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/Dockerfile b/Dockerfile index 6a9e797..4619ec9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -29,5 +29,5 @@ ENV PORT=8000 # 暴露端口 EXPOSE 8000 -# 初始化数据库并启动应用 -CMD ["sh", "-c", "node server/scripts/initDatabase.cjs && node server/index.cjs"] \ No newline at end of file +# 启动应用(数据库初始化在应用启动时自动进行) +CMD ["node", "server/index.cjs"] \ No newline at end of file diff --git a/server/index.cjs b/server/index.cjs index 62a4cbd..c39645f 100644 --- a/server/index.cjs +++ b/server/index.cjs @@ -23,6 +23,31 @@ const PORT = process.env.PORT || 3001; try { dbManager.init(); console.log('数据库连接成功'); + + // 在生产环境中,确保管理员用户存在 + if (process.env.NODE_ENV === 'production') { + const db = dbManager.getDatabase(); + const adminExists = db.prepare('SELECT id FROM users WHERE email = ?').get('admin@localhost'); + + if (!adminExists) { + const bcrypt = require('bcryptjs'); + const adminPassword = bcrypt.hashSync('admin123', 12); + + // 创建管理员用户 + const insertAdmin = db.prepare( + 'INSERT INTO users (email, password_hash) VALUES (?, ?)' + ); + const adminResult = insertAdmin.run('admin@localhost', adminPassword); + + // 创建管理员档案 + const insertAdminProfile = db.prepare( + 'INSERT INTO user_profiles (user_id, full_name, username) VALUES (?, ?, ?)' + ); + insertAdminProfile.run(adminResult.lastInsertRowid, '系统管理员', 'admin'); + + console.log('✅ 管理员用户创建成功'); + } + } } catch (error) { console.error('数据库连接失败:', error); process.exit(1); diff --git a/server/scripts/initDatabase.cjs b/server/scripts/initDatabase.cjs index ccdcd37..eb1fe6f 100644 --- a/server/scripts/initDatabase.cjs +++ b/server/scripts/initDatabase.cjs @@ -38,8 +38,12 @@ async function initializeDatabase() { console.log('ℹ️ 管理员用户已存在'); } - // 创建示例数据(可选) - await createSampleData(db); + // 仅在开发环境创建示例数据 + if (process.env.NODE_ENV !== 'production') { + await createSampleData(db); + } else { + console.log('ℹ️ 生产环境,跳过示例数据创建'); + } console.log('🎉 数据库初始化完成!'); console.log(`📍 数据库文件位置: ${path.resolve('./numerology.db')}`);