/** * 数据库服务提供者 * 负责数据库连接和初始化 */ import knex from 'knex' import { databaseConfig } from '../config/database.js' class DatabaseProvider { constructor() { this.db = null } /** * 初始化数据库连接 */ async register() { try { this.db = knex(databaseConfig) // 测试数据库连接 await this.db.raw('SELECT 1') console.log('✓ 数据库连接成功') // 运行待处理的迁移 await this.runMigrations() return this.db } catch (error) { console.error('✗ 数据库连接失败:', error.message) throw error } } /** * 运行数据库迁移 */ async runMigrations() { try { await this.db.migrate.latest() console.log('✓ 数据库迁移完成') } catch (error) { console.error('✗ 数据库迁移失败:', error.message) throw error } } /** * 获取数据库实例 */ getConnection() { return this.db } /** * 关闭数据库连接 */ async close() { if (this.db) { await this.db.destroy() console.log('✓ 数据库连接已关闭') } } } // 导出单例实例 export default new DatabaseProvider()