go-lemmy/cmd/gen/generator/routes.go

115 lines
2.6 KiB
Go
Raw Permalink Normal View History

package generator
import (
"io"
"strings"
"github.com/dave/jennifer/jen"
"go.elara.ws/go-lemmy/cmd/gen/extractor"
)
type RoutesGenerator struct {
w io.Writer
PkgName string
}
func NewRoutes(w io.Writer, pkgName string) *RoutesGenerator {
return &RoutesGenerator{w, pkgName}
}
func (r *RoutesGenerator) Generate(routes []extractor.Route) error {
f := jen.NewFile(r.PkgName)
2023-04-21 02:27:38 +00:00
f.HeaderComment("Code generated by go.elara.ws/go-lemmy/cmd/gen (routes generator). DO NOT EDIT.")
2023-01-07 22:40:18 +00:00
for _, r := range routes {
f.Comment(r.Summary)
f.Func().Params(
jen.Id("c").Id("*Client"),
2023-09-25 04:48:00 +00:00
).Id(transformName(r.Name)).ParamsFunc(func(g *jen.Group) {
g.Id("ctx").Qual("context", "Context")
if r.ParamsName != "" {
g.Id("data").Id(r.ParamsName)
2023-09-25 04:48:00 +00:00
}
}).ParamsFunc(func(g *jen.Group) {
2023-12-15 17:25:29 +00:00
if r.ReturnName == "map[string]any" {
g.Map(jen.String()).Any()
} else if r.ReturnName != "" {
g.Op("*").Id(r.ReturnName)
}
2023-12-15 17:25:29 +00:00
g.Error()
}).BlockFunc(func(g *jen.Group) {
2023-10-04 23:16:36 +00:00
data := jen.Id("data")
// If there are no parameters, set the data to nil
if r.ParamsName == "" {
data = jen.Nil()
}
returnName := r.ReturnName
if returnName == "" {
returnName = "emptyResponse"
}
2023-12-15 17:25:29 +00:00
if returnName == "map[string]any" {
g.Id("resData").Op(":=").Map(jen.String()).Any().Block()
} else {
g.Id("resData").Op(":=").Op("&").Id(returnName).Block()
}
2023-10-04 23:16:36 +00:00
funcName := "req"
if r.Method == "GET" {
funcName = "getReq"
}
2023-12-15 17:25:29 +00:00
g.List(jen.Id("res"), jen.Err()).Op(":=").Id("c").Dot(funcName).ParamsFunc(func(g *jen.Group) {
g.Id("ctx")
g.Lit(r.Method)
g.Lit(r.Path)
g.Add(data)
if returnName == "map[string]any" {
g.Op("&").Id("resData")
} else {
g.Id("resData")
}
})
g.If(jen.Err().Op("!=").Nil()).BlockFunc(func(g *jen.Group) {
if returnName == "emptyResponse" {
g.Return(jen.Err())
} else {
g.Return(jen.Nil(), jen.Err())
}
})
2023-12-15 17:25:29 +00:00
if r.ReturnName == "map[string]any" {
g.Err().Op("=").Id("resError").Params(jen.Id("res"), jen.Id("NewOptionalNil[string]").Params())
} else {
g.Err().Op("=").Id("resError").Params(jen.Id("res"), jen.Id("resData").Dot("Error"))
}
g.If(jen.Err().Op("!=").Nil()).BlockFunc(func(g *jen.Group) {
if returnName == "emptyResponse" {
g.Return(jen.Err())
} else {
g.Return(jen.Nil(), jen.Err())
}
})
if returnName == "emptyResponse" {
g.Return(jen.Nil())
} else {
g.Return(jen.Id("resData"), jen.Nil())
}
})
}
return f.Render(r.w)
}
2023-01-31 03:38:57 +00:00
func transformName(s string) string {
s = strings.ToUpper(s[:1]) + s[1:]
2023-01-31 03:38:57 +00:00
s = strings.TrimPrefix(s, "Get")
s = strings.TrimPrefix(s, "List")
return s
}