import Fastify from 'fastify'; import cors from '@fastify/cors'; import { config } from './config/env.js'; import { testDatabaseConnection, prisma } from './config/database.js'; const fastify = Fastify({ logger: { level: config.logLevel, transport: { target: 'pino-pretty', options: { colorize: true, translateTime: 'HH:MM:ss Z', ignore: 'pid,hostname', }, }, }, }); // 注册CORS插件 await fastify.register(cors, { origin: true, // 开发环境允许所有来源 credentials: true, }); // 健康检查路由 fastify.get('/health', async () => { // 检查数据库连接 let dbStatus = 'unknown'; try { await prisma.$queryRaw`SELECT 1`; dbStatus = 'connected'; } catch { dbStatus = 'disconnected'; } return { status: 'ok', database: dbStatus, timestamp: new Date().toISOString(), uptime: process.uptime(), }; }); // API路由前缀 fastify.get('/api/v1', async () => { return { message: 'AI Clinical Research Platform API', version: '1.0.0', environment: config.nodeEnv, }; }); // 启动服务器 const start = async () => { try { // 测试数据库连接 console.log('🔍 正在测试数据库连接...'); const dbConnected = await testDatabaseConnection(); if (!dbConnected) { console.error('❌ 数据库连接失败,无法启动服务器'); process.exit(1); } // 启动Fastify服务器 await fastify.listen({ port: config.port, host: config.host, }); console.log('\n' + '='.repeat(60)); console.log('🚀 AI临床研究平台 - 后端服务器启动成功!'); console.log('='.repeat(60)); console.log(`📍 服务地址: http://${config.host === '0.0.0.0' ? 'localhost' : config.host}:${config.port}`); console.log(`🔍 健康检查: http://localhost:${config.port}/health`); console.log(`📡 API入口: http://localhost:${config.port}/api/v1`); console.log(`🌍 运行环境: ${config.nodeEnv}`); console.log('='.repeat(60) + '\n'); } catch (err) { fastify.log.error(err); process.exit(1); } }; start();