|
@@ -0,0 +1,91 @@
|
|
|
+const express = require('express');
|
|
|
+const path = require('path');
|
|
|
+const fs = require('fs');
|
|
|
+const config = require('../config.json');
|
|
|
+const Logger = require('./Logger');
|
|
|
+const MySQL = require('../plugin/MySQL');
|
|
|
+
|
|
|
+class SERVER {
|
|
|
+ constructor() {
|
|
|
+ this.app = express();
|
|
|
+ this.port = config.port || 3000;
|
|
|
+ this.apiDirectory = path.join(__dirname, '../apis'); // API 文件存放目录
|
|
|
+
|
|
|
+ this.logger = new Logger(path.join(__dirname, '../logs/Server.log'), 'INFO');
|
|
|
+
|
|
|
+ // 解析 JSON 请求体
|
|
|
+ this.app.use(express.json());
|
|
|
+
|
|
|
+ // 初始化数据库连接
|
|
|
+ this.db = new MySQL();
|
|
|
+
|
|
|
+ // 加载 API 路由
|
|
|
+ this.loadAPIs(this.apiDirectory);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 测试数据库连接
|
|
|
+ async initDB() {
|
|
|
+ try {
|
|
|
+ await this.db.connect();
|
|
|
+ this.logger.info('数据库连接成功');
|
|
|
+ } catch (error) {
|
|
|
+ this.logger.error(`数据库连接失败: ${error.message}`);
|
|
|
+ process.exit(1);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ loadAPIs(directory) {
|
|
|
+ this.logger.info('==============正在加载API==============');
|
|
|
+
|
|
|
+ const items = fs.readdirSync(directory);
|
|
|
+
|
|
|
+ items.forEach(item => {
|
|
|
+ const itemPath = path.join(directory, item);
|
|
|
+ const stats = fs.statSync(itemPath);
|
|
|
+
|
|
|
+ if (stats.isDirectory()) {
|
|
|
+ // 如果是目录,递归调用
|
|
|
+ this.loadAPIs(itemPath);
|
|
|
+ } else if (stats.isFile() && itemPath.endsWith('.js')) {
|
|
|
+ // 如果是文件且是 JavaScript 文件
|
|
|
+ this.loadAPIFile(itemPath);
|
|
|
+ }
|
|
|
+ });
|
|
|
+
|
|
|
+ this.logger.info('==============API加载完成==============');
|
|
|
+ }
|
|
|
+
|
|
|
+ // 加载单个 API 文件
|
|
|
+ loadAPIFile(filePath) {
|
|
|
+ try {
|
|
|
+ const APIClass = require(filePath);
|
|
|
+
|
|
|
+ for (const key in APIClass) {
|
|
|
+ if (APIClass.hasOwnProperty(key)) {
|
|
|
+ const apiInstance = new APIClass[key]();
|
|
|
+ apiInstance.setupRoute();
|
|
|
+ this.app.use('/', apiInstance.getRouter());
|
|
|
+ this.logger.info(`已加载API文件: ${filePath}`);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ } catch (error) {
|
|
|
+ this.logger.error(`加载API文件失败: ${filePath},错误: ${error.message}`);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ start() {
|
|
|
+ this.logger.info('============正在启动服务器============');
|
|
|
+
|
|
|
+ // 初始化数据库连接
|
|
|
+ this.initDB().then(() => {
|
|
|
+ this.app.listen(this.port, () => {
|
|
|
+ this.logger.info(`==========服务器正在 ${this.port} 上运行==========`);
|
|
|
+ });
|
|
|
+ }).catch(err => {
|
|
|
+ this.logger.error(`启动服务器失败: ${err.message}`);
|
|
|
+ process.exit(1); // 启动失败时退出进程
|
|
|
+ });
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+module.exports = SERVER;
|