Quellcode durchsuchen

♻️ refactor(server): 重构服务器初始化和路由加载逻辑

- 优化代码格式和注释,移除多余空行和注释
- 统一变量命名和代码风格,增强可读性
- 调整服务器实例创建代码格式,修复语法问题

✨ feat(server): 实现开发环境API路由动态加载

- 添加API路由动态加载中间件,支持开发环境热更新
- 分离开发/生产环境路由加载逻辑,优化启动流程
- 增加API请求路径检测,仅对/api、/ui、/doc路径应用动态路由

📝 docs(server): 更新代码注释

- 简化冗余注释,提高注释准确性
- 统一注释风格,移除不必要的注释内容

🔧 chore(server): 环境配置优化

- 添加dotenv配置导入,支持环境变量加载
- 优化进程终止信号处理逻辑,移除重复注释
yourname vor 4 Monaten
Ursprung
Commit
03f4a4fde7
1 geänderte Dateien mit 57 neuen und 26 gelöschten Zeilen
  1. 57 26
      server.js

+ 57 - 26
server.js

@@ -1,20 +1,19 @@
+import 'dotenv/config'
 import fs from 'node:fs/promises';
 import { URL } from 'node:url';
 import { Transform } from 'node:stream';
 import { Readable } from 'node:stream';
-import { pipeline } from 'node:stream/promises';
 import { Hono } from 'hono';
-import { logger } from 'hono/logger'; // 引入 Hono 日志中间件
+import { logger } from 'hono/logger';
 import { createServer as createNodeServer } from 'node:http';
 import process from 'node:process';
 import { createAdaptorServer } from '@hono/node-server'  
 
-
 // 创建 Hono 应用
-const app = new Hono();// API路由
+const app = new Hono();
 
-// 全局使用 Hono 日志中间件(记录所有请求)
-app.use('*', logger()); // 新增:添加请求日志中间件
+// 全局使用 Hono 日志中间件
+app.use('*', logger());
 
 // 常量定义
 const isProduction = process.env.NODE_ENV === 'production';
@@ -29,17 +28,17 @@ console.log(`端口: ${port}`);
 console.log(`基础路径: ${base}`);
 console.log('========================================');
 
-// 解析基础路径为 URL 对象,方便后续处理
+// 解析基础路径为 URL 对象
 const baseUrl = new URL(base, `http://localhost:${port}`);
 console.log(`基础URL解析完成: ${baseUrl.href}`);
 
-// 创建服务器实例  
+// 创建服务器实例
 console.log('正在创建服务器实例...');
 const parentServer = createAdaptorServer({  
   fetch: app.fetch,  
   createServer: createNodeServer,  
   port: port,  
-})  
+})
 console.log('服务器实例创建成功');
 
 // 生产环境中间件
@@ -62,18 +61,18 @@ if (!isProduction) {
   console.log('开发环境: 初始化 Vite 开发服务器...');
   const { createServer } = await import('vite');
   vite = await createServer({
-    server: { middlewareMode: {
+    server: { 
+      middlewareMode: {
         server: parentServer
       },
       hmr: {  
         port: 8081,
-        clientPort: 443, // 或其他可用端口  
+        clientPort: 443,
         path: 'vite-hmr'
       },
       proxy: {
         '/vite-hmr': {
           target: 'ws://localhost:8081',
-          // 代理 WebSocket
           ws: true,
         },
       },
@@ -84,18 +83,52 @@ if (!isProduction) {
   console.log('Vite 开发服务器初始化完成');
 }
 
-// 加载 API 路由
-if (!isProduction) {
-  console.log('开发环境: 从 Vite 加载 API 路由...');
-  const apiModule = await vite.ssrLoadModule('./src/server/api.ts');
-  app.route('/', apiModule.default);
-  console.log('API 路由加载完成');
-}else{
+// 生产环境:启动时加载 API 路由
+if (isProduction) {
   console.log('生产环境: 加载编译后的 API 路由...');
-  const api = (await import('./dist/api/api.js')).default
+  const api = (await import('./dist/api/api.js')).default;
   app.route('/', api);
   console.log('API 路由加载完成');
 }
+// 开发环境:不在此处加载 API 路由,改为在中间件中动态加载
+
+// 添加动态 API 路由中间件
+app.use(async (c, next) => {
+  try {
+    // 开发环境:每次请求动态加载 API 路由
+    if (!isProduction && vite) {
+      // 动态加载最新 API 模块
+      const apiModule = await vite.ssrLoadModule('./src/server/api.ts');
+      
+      // 创建临时子应用并挂载路由
+      const apiApp = new Hono();
+      apiApp.route('/', apiModule.default);
+      
+      // 检查是否为 API 请求
+      if (
+        c.req.path.startsWith('/api')
+        || c.req.path.startsWith('/ui')
+        || c.req.path.startsWith('/doc')
+      ) {
+        // 直接由子应用处理 API 请求
+        return apiApp.fetch(c.req.raw, {
+          ...c.env,
+          // 传递原始请求对象
+          incoming: c.env.incoming,
+          outgoing: c.env.outgoing
+        });
+      }
+    }
+
+    await next();
+  } catch (e) {
+    if (!isProduction && vite) {
+      vite.ssrFixStacktrace(e);
+    }
+    console.error('API 路由加载错误:', e.stack);
+    return c.text('API 服务器错误', 500);
+  }
+});
 
 // 请求处理中间件 - 通用逻辑
 app.use(async (c, next) => {
@@ -156,7 +189,6 @@ app.use(async (c, next) => {
 
 // 请求处理中间件 - SSR 渲染逻辑
 app.use(async (c) => {
-  
   try {
     // 使用 c.env 获取原生请求响应对象
     const req = c.env.incoming;
@@ -303,7 +335,6 @@ app.use(async (c) => {
   }
 });
 
-
 // 启动服务器
 console.log('准备启动服务器...');
 parentServer.listen(port, () => {  
@@ -322,7 +353,7 @@ const shutdownServer = async () => {
   if (!isProduction && vite) {
     console.log('正在关闭 Vite 开发服务器(包括 HMR 服务)...');
     try {
-      await vite.close(); // 关闭 Vite 实例,会自动终止 HMR 服务(8081 端口)
+      await vite.close();
       console.log('Vite 开发服务器已关闭');
     } catch (err) {
       console.error('关闭 Vite 服务器时出错:', err);
@@ -340,6 +371,6 @@ const shutdownServer = async () => {
   });
 };
 
-// 处理进程终止信号(包括 Ctrl+C)
-process.on('SIGINT', shutdownServer);  // 处理 Ctrl+C
-process.on('SIGTERM', shutdownServer); // 处理 kill 命令
+// 处理进程终止信号
+process.on('SIGINT', shutdownServer);
+process.on('SIGTERM', shutdownServer);