mycroforge/MycroForge.CLI/Commands/MycroForge.Api.Generate.Router.cs

76 lines
2.8 KiB
C#

using System.CommandLine;
using Humanizer;
using MycroForge.CLI.CodeGen;
using MycroForge.Core.Contract;
using MycroForge.CLI.Extensions;
using MycroForge.Core;
namespace MycroForge.CLI.Commands;
public partial class MycroForge
{
public partial class Api
{
public partial class Generate
{
public class Router : Command, ISubCommandOf<Generate>
{
private static readonly string[] Template =
[
"from fastapi import APIRouter",
"from fastapi.responses import JSONResponse",
"from fastapi.encoders import jsonable_encoder",
"",
"router = APIRouter()",
"",
"@router.get(\"/{name}\")",
"async def index(name: str):",
"\treturn JSONResponse(status_code=200, content=jsonable_encoder({'greeting': f\"Hello, {name}!\"}))"
];
private static readonly Argument<string> NameArgument =
new(name: "name", description: "The name of the api router");
private readonly ProjectContext _context;
public Router(ProjectContext context) : base("router", "Generate an api router")
{
_context = context;
AddAlias("r");
AddArgument(NameArgument);
this.SetHandler(ExecuteAsync, NameArgument);
}
private async Task ExecuteAsync(string name)
{
var fqn = new FullyQualifiedName(name);
var folderPath = $"{Features.Api.FeatureName}/routers";
_context.AssertDirectoryExists(folderPath);
if (fqn.HasPath)
folderPath = Path.Combine(folderPath, fqn.Path);
var fileName = $"{fqn.SnakeCasedName}.py";
var filePath = Path.Combine(folderPath, fileName);
await _context.CreateFile(filePath, Template);
var moduleImportPath = folderPath
.Replace('\\', '.')
.Replace('/', '.');
var main = await _context.ReadFile("main.py");
main = new MainModifier(main)
.Initialize()
.Import(from: moduleImportPath, import: fqn.SnakeCasedName)
.IncludeRouter(prefix: name.Kebaberize(), router: fqn.SnakeCasedName)
.Rewrite();
await _context.WriteFile("main.py", main);
}
}
}
}
}