using MycroForge.CLI.Commands; using MycroForge.Core; namespace MycroForge.CLI.Features; public sealed partial class Api : IFeature { #region Templates private static readonly string[] RouterTemplate = [ "from fastapi import APIRouter", "from fastapi.responses import JSONResponse", "from fastapi.encoders import jsonable_encoder", "", "router = APIRouter()", "", "@router.get(\"/{name}\")", "async def hello(name: str):", "\treturn JSONResponse(status_code=200, content=jsonable_encoder({'greeting': f\"Hello, {name}!\"}))" ]; private static readonly string[] MainTemplate = [ "from fastapi import FastAPI", $"from {FeatureName}.routers import hello", "", "app = FastAPI()", "", "app.include_router(prefix=\"/hello\", router=hello.router)" ]; #endregion public const string FeatureName = "api"; public string Name => FeatureName; private readonly OptionsContainer _optionsContainer; public Api(OptionsContainer optionsContainer) { _optionsContainer = optionsContainer; } public async Task ExecuteAsync(ProjectContext context) { var options = _optionsContainer.Get(); var config = await context.LoadConfig(create: true); config.Api = new() { Port = options.ApiPort ?? 8000 }; await context.SaveConfig(config); await context.Bash( "source .venv/bin/activate", "python3 -m pip install fastapi", "python3 -m pip freeze > requirements.txt" ); await context.CreateFile($"{FeatureName}/routers/hello.py", RouterTemplate); var main = await context.ReadFile("main.py"); main = string.Join('\n', MainTemplate) + main; await context.WriteFile("main.py", main); } }