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

73 lines
2.8 KiB
C#

using System.CommandLine;
using Humanizer;
using MycroForge.CLI.Commands.Interfaces;
using MycroForge.CLI.Extensions;
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 folderPath = $"{Features.Api.FeatureName}/routers";
_context.AssertDirectoryExists(folderPath);
if (name.FullyQualifiedName() is { Length: 2 } fullName)
{
folderPath = Path.Join(folderPath, fullName[0]);
name = fullName[1];
}
var moduleImportPath = folderPath.Replace('\\', '.').Replace('/', '.');
var moduleName = name.Underscore().ToLower();
var fileName = $"{moduleName}.py";
var filePath = Path.Join(folderPath, fileName);
await _context.CreateFile(filePath, Template);
var main = await _context.ReadFile("main.py");
main += string.Join('\n',
$"\n\nfrom {moduleImportPath} import {moduleName}",
$"app.include_router(prefix=\"/{name.Kebaberize()}\", router={moduleName}.router)"
);
await _context.WriteFile("main.py", main);
}
}
}
}
}