56 lines
2.1 KiB
C#
56 lines
2.1 KiB
C#
using System.CommandLine;
|
|
using Humanizer;
|
|
using MycroForge.CLI.Commands.Interfaces;
|
|
|
|
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 moduleName = name.Underscore();
|
|
await _context.CreateFile($"api/routers/{moduleName}.py", Template);
|
|
|
|
var main = await _context.ReadFile("main.py");
|
|
main += string.Join('\n',
|
|
$"\nfrom api.routers import {moduleName}",
|
|
$"app.include_router(prefix=\"/{name.Kebaberize()}\", router={moduleName}.router)\n"
|
|
);
|
|
await _context.WriteFile("main.py", main);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} |