Переглянути джерело

♻️ refactor(server): move database initialization to API middleware

- 将数据库初始化逻辑从全局作用域移至/api/v1/*路由中间件
- 确保数据库仅在首次API请求时初始化,优化应用启动流程
- 移除重复的注释代码块,清理代码结构
yourname 1 місяць тому
батько
коміт
b5a5b0292d
1 змінених файлів з 21 додано та 21 видалено
  1. 21 21
      packages/server/src/index.ts

+ 21 - 21
packages/server/src/index.ts

@@ -22,23 +22,6 @@ import { MerchantMt } from '@d8d/merchant-module-mt'
 import { OrderMt, OrderGoodsMt, OrderRefundMt } from '@d8d/orders-module-mt'
 import { SupplierMt } from '@d8d/supplier-module-mt'
 
-if(!AppDataSource || !AppDataSource.isInitialized) {
-  initializeDataSource([
-    // 已实现的包实体
-    UserEntityMt, RoleMt, FileMt,
-    TenantEntityMt,
-    AreaEntityMt, PaymentMtEntity,
-    Advertisement, AdvertisementType,
-    DeliveryAddressMt,
-    GoodsMt, GoodsCategoryMt,
-    MerchantMt,
-    OrderMt, OrderGoodsMt, OrderRefundMt,
-    SupplierMt
-  ])
-  await AppDataSource.initialize();
-  console.log('数据库初始化完成')
-}
-
 const app = new Hono();
 const api = new OpenAPIHono<AuthContext>()
 
@@ -50,10 +33,27 @@ api.use('/api/v1/*', async (_, next) => {
   await next()
 })
 
-// // 数据库初始化中间件
-// api.use('/api/v1/*', async (c, next) => {
-//   await next();
-// })
+// 数据库初始化中间件
+api.use('/api/v1/*', async (c, next) => {
+  if(!AppDataSource || !AppDataSource.isInitialized) {
+    initializeDataSource([
+      // 已实现的包实体
+      UserEntityMt, RoleMt, FileMt,
+      TenantEntityMt,
+      AreaEntityMt, PaymentMtEntity,
+      Advertisement, AdvertisementType,
+      DeliveryAddressMt,
+      GoodsMt, GoodsCategoryMt,
+      MerchantMt,
+      OrderMt, OrderGoodsMt, OrderRefundMt,
+      SupplierMt
+    ])
+    await AppDataSource.initialize();
+    console.log('数据库初始化完成')
+  }
+  
+  await next();
+})
 
 // 注册Bearer认证方案
 api.openAPIRegistry.registerComponent('securitySchemes','bearerAuth',{