refactor: extract intelligent routing to unified.js

- Created new src/routes/unified.js (225 lines)
  - detectBackendFromModel(): Detects backend from model name
  - routeToBackend(): Routes to Claude/OpenAI/Gemini with permission checks
  - POST /v1/chat/completions: OpenAI-compatible endpoint with intelligent routing
  - POST /v1/completions: Legacy completions endpoint with intelligent routing

- Updated src/routes/api.js (reduced from 1185 to 968 lines)
  - Removed ~217 lines of routing logic
  - Kept Claude-specific endpoints (/api/v1/messages)
  - Maintained all other Claude API functionality

- Updated src/app.js
  - Added unifiedRoutes registration at /api prefix

Benefits:
- Single responsibility: api.js focuses on Claude API routes
- Better organization: routing logic isolated in unified.js
- Easier maintenance: changes to routing won't affect Claude code
- File size reduction: api.js reduced by 18%

Tested:
-  Claude model routing via /v1/chat/completions
-  OpenAI model routing (correct backend detection)
-  Gemini model routing (correct backend detection)
-  Legacy /v1/completions endpoint
-  All tests pass, no regressions

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
jft0m
2025-10-14 14:30:23 +00:00
parent e540ec3a52
commit 344599f318
3 changed files with 227 additions and 217 deletions

View File

@@ -14,6 +14,7 @@ const cacheMonitor = require('./utils/cacheMonitor')
// Import routes
const apiRoutes = require('./routes/api')
const unifiedRoutes = require('./routes/unified')
const adminRoutes = require('./routes/admin')
const webRoutes = require('./routes/web')
const apiStatsRoutes = require('./routes/apiStats')
@@ -256,6 +257,7 @@ class Application {
// 🛣️ 路由
this.app.use('/api', apiRoutes)
this.app.use('/api', unifiedRoutes) // 统一智能路由(支持 /v1/chat/completions 等)
this.app.use('/claude', apiRoutes) // /claude 路由别名,与 /api 功能相同
this.app.use('/admin', adminRoutes)
this.app.use('/users', userRoutes)