feat(api): 新增客户端添加功能并优化路由加载

- 新增客户端添加 API,实现客户端信息的添加和处理
- 重构路由加载函数,支持递归加载子目录中的路由文件
- 添加日志记录,便于调试和监控
- 优化 HTTP 请求处理,增加错误处理和状态码检查
This commit is contained in:
aixianling
2025-02-26 14:16:26 +08:00
parent 7ab5d7dbbf
commit b958beaf2f
5 changed files with 87 additions and 21 deletions

49
app.js
View File

@@ -12,20 +12,46 @@ app.use(bodyParser()); // 添加在路由中间件之前
const router = new Router();
// 自动加载API路由函数
const loadAPIRoutes = () => {
const apiDir = path.join(__dirname, "api");
const files = fs.readdirSync(apiDir);
const loadAPIRoutes = (baseDir = 'api', baseRoute = '/api') => {
const scanDirectory = (dir, routePrefix) => {
const entries = fs.readdirSync(dir, { withFileTypes: true });
files.forEach((file) => {
if (file.endsWith(".js") && file !== "index.js") {
const routePath = `/api/${file.replace(".js", "")}`;
const handler = require(path.join(apiDir, file));
entries.forEach(entry => {
const fullPath = path.join(dir, entry.name);
const relativePath = path.relative(baseDir, dir);
// 构建路由路径:工程目录结构 -> URL路径
const routePath = path.join(
routePrefix,
relativePath,
entry.name.replace(/\.js$/, '')
).replace(/\\/g, '/'); // Windows路径转URL路径
router.post(routePath, async (ctx) => {
await handler(ctx);
});
if (entry.isDirectory()) {
scanDirectory(fullPath, routePrefix); // 递归扫描子目录
} else if (
entry.isFile() &&
path.extname(entry.name) === '.js' &&
entry.name !== 'index.js'
) {
registerRoute(fullPath, routePath);
}
});
};
// 路由注册器支持扩展其他HTTP方法
const registerRoute = (filePath, routePath) => {
try {
const handler = require(filePath);
router.post(routePath, async ctx => await handler(ctx));
console.log(`[Route] POST ${routePath} -> ${filePath}`);
} catch (err) {
console.error(`[Error] Failed to load route ${routePath}:`, err);
}
});
};
// 初始化扫描
scanDirectory(path.join(__dirname, baseDir), baseRoute);
};
// 公开路由
@@ -50,7 +76,6 @@ app.use(async (ctx, next) => {
}
await next();
});
// JWT中间件保护下方所有路由
app.use(
koaJwt({