hn-hlw-service/test-startup.js
2026-07-27 11:28:33 +08:00

77 lines
2.0 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env node
/**
* 应用启动测试脚本
* 快速验证应用是否能正常启动
*/
// 加载环境变量
const envFile = `.env.${process.env.NODE_ENV || "development"}`;
require("dotenv").config({ path: envFile });
const express = require("express");
const { connectToMongoDB, getDatabase } = require('./mongodb');
async function testStartup() {
console.log('🚀 测试应用启动...');
try {
// 1. 测试数据库连接
console.log('1⃣ 连接数据库...');
await connectToMongoDB();
console.log('✅ 数据库连接成功');
// 2. 测试获取数据库实例
console.log('2⃣ 测试数据库实例...');
const db = await getDatabase("admin");
await db.admin().ping();
console.log('✅ 数据库实例正常');
// 3. 测试Express应用
console.log('3⃣ 创建Express应用...');
const app = express();
app.use(express.json());
// 简单的健康检查路由
app.get('/health', (req, res) => {
res.json({ status: 'ok', timestamp: new Date().toISOString() });
});
// 测试数据库路由
app.get('/test-db', async (req, res) => {
try {
const db = await getDatabase("admin");
await db.admin().ping();
res.json({ database: 'connected', status: 'ok' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// 启动服务器
const port = process.env.CONFIG_NODE_PORT || 3000;
const server = app.listen(port, () => {
console.log(`✅ 服务器启动成功,端口: ${port}`);
});
// 等待一会儿然后关闭
setTimeout(() => {
console.log('4⃣ 关闭测试服务器...');
server.close(() => {
console.log('✅ 服务器已关闭');
process.exit(0);
});
}, 3000);
} catch (error) {
console.error('❌ 启动测试失败:', error.message);
process.exit(1);
}
}
// 运行测试
if (require.main === module) {
testStartup();
}
module.exports = { testStartup };