# -*- coding: utf-8 -*- """ JavaScript NestJS 后端项目初始化模块 """ import subprocess import sys import shutil def run_command_interactive(cmd, cwd, description): """运行命令并支持用户交互""" print(f"\n{'=' * 60}") print(f"执行: {description}") print(f"{'=' * 60}") print(f"💡 提示: 此步骤可能需要您进行交互操作") print(f"{'=' * 60}\n") try: result = subprocess.run(cmd, cwd=cwd, shell=True) print(f"\n{'=' * 60}") if result.returncode == 0: print(f"✅ {description} - 完成") else: print(f"❌ {description} - 失败 (错误码: {result.returncode})") print(f"{'=' * 60}\n") return result.returncode == 0 except Exception as e: print(f"\n❌ 执行失败: {str(e)}") return False def run_command_with_progress(cmd, cwd, description): """运行命令并显示实时输出""" try: print(f"\n{'=' * 60}") print(f"执行: {description}") print(f"{'=' * 60}") process = subprocess.Popen( cmd, cwd=cwd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=0 ) for line in process.stdout: try: decoded_line = line.decode('utf-8', errors='replace') except: try: decoded_line = line.decode('gbk', errors='replace') except: decoded_line = line.decode('latin-1', errors='replace') print(decoded_line, end='') process.wait() if process.returncode == 0: print(f"\n{'=' * 60}") print(f"✅ {description} - 完成") print(f"{'=' * 60}\n") return True else: print(f"\n{'=' * 60}") print(f"❌ {description} - 失败 (错误码: {process.returncode})") print(f"{'=' * 60}\n") return False except Exception as e: print(f"\n❌ 执行失败: {str(e)}") return False def init_nestjs_project(backend_dir, project_name): """初始化 NestJS 项目""" print("\n🚀 初始化 NestJS 项目...") print("\n⚠️ 重要提示:") print(" 1. NestJS CLI 会询问使用哪个包管理器,建议选择 npm") print(" 2. 创建过程可能需要几分钟,请耐心等待\n") # 删除空目录,因为 NestJS CLI 需要创建目录 backend_dir.rmdir() # 使用 NestJS CLI 创建项目 success = run_command_interactive( f"npx @nestjs/cli new {backend_dir.name} --skip-git", backend_dir.parent, "创建 NestJS 项目" ) if not success: # 如果失败,重新创建目录 backend_dir.mkdir(exist_ok=True) print("\n💡 提示: 请确保已安装 Node.js 和 npm") print(" 下载地址: https://nodejs.org/") sys.exit(1) # 检查目录是否创建成功 if not backend_dir.exists(): print("❌ 项目目录创建失败") sys.exit(1) # 修改默认端口为 8080 并添加 CORS main_ts = backend_dir / "src" / "main.ts" if main_ts.exists(): main_ts.write_text(f'''import {{ NestFactory }} from '@nestjs/core'; import {{ AppModule }} from './app.module'; async function bootstrap() {{ const app = await NestFactory.create(AppModule); // 启用 CORS app.enableCors(); // 设置全局前缀 app.setGlobalPrefix('api'); await app.listen(8080); console.log('🚀 服务器启动: http://localhost:8080'); console.log('📍 健康检查: http://localhost:8080/api/health'); }} bootstrap(); ''', encoding='utf-8') # 修改 AppController 添加健康检查 app_controller = backend_dir / "src" / "app.controller.ts" if app_controller.exists(): app_controller.write_text(f'''import {{ Controller, Get }} from '@nestjs/common'; import {{ AppService }} from './app.service'; @Controller() export class AppController {{ constructor(private readonly appService: AppService) {{}} @Get('health') health() {{ return {{ status: 'ok', message: 'Welcome to {project_name} API', }}; }} @Get('hello') getHello(): string {{ return this.appService.getHello(); }} }} ''', encoding='utf-8') print("\n✅ NestJS 项目初始化成功") print("💡 启动命令: npm run start:dev (开发模式) 或 npm run start (生产模式)") print("📚 NestJS 文档: https://docs.nestjs.com/")