Server.js 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. const express = require('express')
  2. const cors = require('cors')
  3. const path = require('path')
  4. const fs = require('fs')
  5. const config = require('../config.json')
  6. const Logger = require('./Logger')
  7. const MySQL = require('../plugin/DataBase/MySQL')
  8. const mq = require('../plugin/mq')
  9. class SERVER {
  10. constructor() {
  11. this.app = express()
  12. this.port = config.port || 3000
  13. this.apiDirectory = path.join(__dirname, '../apis') // API 文件存放目录
  14. this.logger = new Logger(path.join(__dirname, '../logs/Server.log'), 'INFO')
  15. // 解析 JSON 请求体
  16. this.app.use(express.json())
  17. //解决cors跨域
  18. this.app.use(cors())
  19. //使用静态资源
  20. this.app.use('/uploads', express.static('./uploads'))
  21. this.app.use('/models', express.static('./models'))
  22. // 初始化数据库连接
  23. this.db = new MySQL()
  24. // 加载 API 路由
  25. this.loadAPIs(this.apiDirectory)
  26. }
  27. // 测试数据库连接
  28. async initDB() {
  29. try {
  30. this.logger.info('正在测试数据库连接')
  31. await this.db.connect()
  32. await this.db.close()
  33. } catch (error) {
  34. this.logger.error(`数据库连接失败: ${error.stack}`)
  35. process.exit(1)
  36. }
  37. }
  38. // 测试MQ连接
  39. async initMQ() {
  40. try {
  41. await mq.init()
  42. const ch = await mq.getChannel('health')
  43. await ch.assertQueue('mq_health_check', { durable: false })
  44. this.logger.info('✅ RabbitMQ 初始化 & 测试成功')
  45. } catch (e) {
  46. this.logger.error('❌ RabbitMQ 初始化失败')
  47. process.exit(1)
  48. }
  49. }
  50. loadAPIs(directory) {
  51. const items = fs.readdirSync(directory)
  52. items.forEach(item => {
  53. const itemPath = path.join(directory, item)
  54. const stats = fs.statSync(itemPath)
  55. if (stats.isDirectory()) {
  56. // 如果是目录,递归调用
  57. this.loadAPIs(itemPath)
  58. } else if (stats.isFile() && itemPath.endsWith('.js')) {
  59. // 如果是文件且是 JavaScript 文件
  60. this.loadAPIFile(itemPath)
  61. }
  62. })
  63. }
  64. // 加载单个 API 文件
  65. loadAPIFile(filePath) {
  66. try {
  67. const APIClass = require(filePath)
  68. for (const key in APIClass) {
  69. if (APIClass.hasOwnProperty(key)) {
  70. const apiInstance = new APIClass[key]()
  71. apiInstance.setupRoute()
  72. this.app.use('/', apiInstance.getRouter())
  73. this.logger.info(`已加载API:${apiInstance.path} 类型:${apiInstance.method}`)
  74. }
  75. }
  76. } catch (error) {
  77. this.logger.error(`加载API文件失败: ${filePath},错误: ${error.stack}`)
  78. }
  79. }
  80. start() {
  81. this.logger.info('============正在启动服务器============')
  82. // 初始化数据库连接
  83. this.initDB().then(() => {
  84. this.initMQ().then(() => {
  85. this.app.listen(this.port, () => {
  86. this.logger.info(`==========服务器正在 ${this.port} 端口上运行==========`)
  87. })
  88. }).catch(err => {
  89. this.logger.error(`启动服务器失败: ${err.message}`)
  90. })
  91. }).catch(err => {
  92. this.logger.error(`启动服务器失败: ${err.message}`)
  93. process.exit(1) // 启动失败时退出进程
  94. })
  95. }
  96. }
  97. module.exports = SERVER