mycroforge/MycroForge.CLI/Features/Api.cs

55 lines
1.6 KiB
C#

namespace MycroForge.CLI.Features;
public sealed class Api : IFeature
{
#region Main
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;
public async Task ExecuteAsync(ProjectContext context)
{
var config = await context.LoadConfig();
config.Api = new() { Port = 8000 };
await context.SaveConfig(config);
await context.Bash(
"source .venv/bin/activate",
"python3 -m pip install fastapi uvicorn[standard]",
"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);
}
}