Server.js 2.9 KB

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