Some checks are pending
Deploy to Production / deploy (push) Waiting to run
- Changed admin frontend port from 3000 to 3300 across all configuration files - Changed API backend port from 3001 to 3301 across all configuration files - Updated health check endpoints to use new ports in CI/CD workflow - Modified documentation and deployment guides to reflect new port numbers - Updated Caddy and Nginx reverse proxy configurations to use new ports
5.9 KiB
5.9 KiB
AI Generate Refactoring Summary
Overview
Refactored src/ai-generate.ts (453 lines) into a clean, maintainable architecture with proper separation of concerns.
New Structure
apps/api/src/
├── routes/
│ └── ai.routes.ts # 85 lines - Clean route handlers
├── services/
│ ├── ai/
│ │ ├── AIService.ts # 48 lines - Main orchestrator
│ │ ├── contentGenerator.ts # 145 lines - Content generation
│ │ ├── metadataGenerator.ts # 63 lines - Metadata generation
│ │ └── altTextGenerator.ts # 88 lines - Alt text generation
│ └── openai/
│ └── client.ts # 36 lines - Singleton client
├── utils/
│ ├── imageUtils.ts # 65 lines - Image utilities
│ ├── contextBuilder.ts # 59 lines - Context building
│ ├── responseParser.ts # 63 lines - Response parsing
│ └── errorHandler.ts # 60 lines - Error handling
├── types/
│ └── ai.types.ts # 87 lines - Type definitions
└── config/
└── prompts.ts # 104 lines - Prompt templates
Benefits Achieved
✅ Maintainability
- Before: 453 lines in one file
- After: 12 focused files, largest is 145 lines
- Each module has a single, clear responsibility
- Easy to locate and fix bugs
✅ Testability
- Service methods can be unit tested independently
- Utilities can be tested in isolation
- OpenAI client can be easily mocked
- Clear interfaces for all components
✅ Reusability
- Utils can be used across different endpoints
- Service can be used outside routes (CLI, jobs, etc.)
- Prompts centralized and easy to modify
- Image handling logic shared
✅ Type Safety
- Full TypeScript coverage with explicit interfaces
- Request/response types defined
- Compile-time error detection
- Better IDE autocomplete and refactoring support
✅ Error Handling
- Centralized error handling with consistent format
- Detailed logging with request IDs
- Debug mode for development
- Structured error responses
Key Improvements
1. Separation of Concerns
- Routes: Only handle HTTP request/response
- Services: Business logic and AI orchestration
- Utils: Reusable helper functions
- Config: Static configuration and prompts
- Types: Type definitions and interfaces
2. OpenAI Client Singleton
- Single instance with optimized configuration
- 10-minute timeout for long requests
- 2 retry attempts for transient failures
- Shared across all AI operations
3. Specialized Generators
ContentGenerator: Handles gpt-5-2025-08-07 with Chat Completions APIMetadataGenerator: Handles gpt-5-2025-08-07 for metadataAltTextGenerator: Handles gpt-5-2025-08-07 for accessibility
4. Utility Functions
imageUtils: Presigned URLs, format validation, placeholder extractioncontextBuilder: Build context from transcriptions and imagesresponseParser: Parse AI responses, strip HTML, handle JSONerrorHandler: Consistent error logging and responses
5. Request Tracking
- Every request gets a unique UUID
- Logs include request ID for correlation
- Elapsed time tracking
- Detailed error context
Migration Status
✅ Completed
- Type definitions
- Configuration extraction
- Utility functions
- OpenAI client singleton
- Service layer implementation
- Route handlers refactored
- TypeScript compilation verified
🔄 Active
- New routes active at
/api/ai/* - Old
ai-generate.tskept as backup (commented out)
📋 Next Steps
-
Test all endpoints:
- POST
/api/ai/generate - POST
/api/ai/generate-metadata - POST
/api/ai/generate-alt-text
- POST
-
Verify functionality:
- Content generation with reference images
- Metadata generation from HTML
- Alt text with and without captions
- Error handling and logging
-
Remove old code (after validation):
- Delete
src/ai-generate.ts - Remove commented import in
index.ts
- Delete
Testing Commands
# Start API server
cd apps/api
pnpm run dev
# Test content generation
curl -X POST http://localhost:3301/api/ai/generate \
-H "Content-Type: application/json" \
-d '{"prompt": "Write about TypeScript best practices"}'
# Test metadata generation
curl -X POST http://localhost:3301/api/ai/generate-metadata \
-H "Content-Type: application/json" \
-d '{"contentHtml": "<h1>Test Article</h1><p>Content here</p>"}'
# Test alt text generation
curl -X POST http://localhost:3301/api/ai/generate-alt-text \
-H "Content-Type: application/json" \
-d '{"placeholderDescription": "dashboard_screenshot"}'
Rollback Plan
If issues arise, rollback is simple:
-
Edit
src/index.ts:// Comment out new routes // app.use('/api/ai', aiRoutesNew); // Uncomment old routes app.use('/api/ai', aiGenerateRouter); -
Restart server
-
Old functionality restored immediately
File Size Comparison
| Metric | Before | After |
|---|---|---|
| Single file | 453 lines | - |
| Largest file | 453 lines | 145 lines |
| Total files | 1 | 12 |
| Average file size | 453 lines | ~70 lines |
| Cyclomatic complexity | High | Low |
Code Quality Metrics
- ✅ Single Responsibility Principle
- ✅ Dependency Injection ready
- ✅ Easy to mock for testing
- ✅ Clear module boundaries
- ✅ Consistent error handling
- ✅ Comprehensive logging
- ✅ Type-safe throughout
Conclusion
The refactoring successfully transformed a complex 453-line file into a clean, maintainable architecture with 12 focused modules. Each component has a clear purpose, is independently testable, and follows TypeScript best practices.
Status: ✅ Ready for testing Risk: Low (old code preserved for easy rollback) Impact: High (significantly improved maintainability)