mycroforge/MycroForge.CLI/Features/Api.cs
Donné Napo 21f4e7765b
All checks were successful
Test MycroForge.CLI / test (push) Has been skipped
Added uvicorn to API feature
2024-10-24 11:52:37 +02:00

65 lines
1.9 KiB
C#

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<Options>();
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 uvicorn",
"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);
}
}