Server.js 3.0 KB

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