73 lines
2.7 KiB
C#
73 lines
2.7 KiB
C#
using System.CommandLine;
|
|
using Humanizer;
|
|
using MycroForge.CLI.CodeGen;
|
|
using MycroForge.Core.Contract;
|
|
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 routersFolderPath = Path.Join(Features.Api.FeatureName, "routers");
|
|
|
|
if (fqn.HasNamespace)
|
|
routersFolderPath = Path.Join(routersFolderPath, fqn.Namespace);
|
|
|
|
var fileName = $"{fqn.SnakeCasedName}.py";
|
|
var filePath = Path.Join(routersFolderPath, fileName);
|
|
|
|
await _context.CreateFile(filePath, Template);
|
|
|
|
var moduleImportPath = routersFolderPath
|
|
.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);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} |