(goctl): fix nested struct generation (#4281)

This commit is contained in:
kesonan
2024-07-28 23:40:25 +08:00
committed by GitHub
parent eeda6efae7
commit ee643a945e
6 changed files with 32 additions and 17 deletions

View File

@@ -157,8 +157,8 @@ func convertDataType(api *spec.ApiSpec, isLegacy bool) (error, *DartSpec) {
defineStruct, ok := ty.(spec.DefineStruct)
if ok {
for index, member := range defineStruct.Members {
structMember, ok := member.Type.(spec.DefineStruct)
if ok && structMember.IsNestedStruct() {
structMember, ok := member.Type.(spec.NestedStruct)
if ok {
defineStruct.Members[index].Type = spec.PrimitiveType{RawName: member.Name}
t := template.New("dataTemplate")
t = t.Funcs(funcMap)

View File

@@ -63,8 +63,8 @@ func writeProperty(writer io.Writer, name, tag, comment string, tp spec.Type, in
err error
isNestedStruct bool
)
structType, ok := tp.(spec.DefineStruct)
if ok && structType.IsNestedStruct() {
structType, ok := tp.(spec.NestedStruct)
if ok {
isNestedStruct = true
}
if len(comment) > 0 {

View File

@@ -30,9 +30,19 @@ func (t DefineStruct) Documents() []string {
return t.Docs
}
// IsNestedStruct returns whether the structure is nested.
func (t DefineStruct) IsNestedStruct() bool {
return len(t.Members) > 0
// Name returns a structure string, such as User
func (t NestedStruct) Name() string {
return t.RawName
}
// Comments returns the comments of struct
func (t NestedStruct) Comments() []string {
return nil
}
// Documents returns the documents of struct
func (t NestedStruct) Documents() []string {
return t.Docs
}
// Name returns a map string, such as map[string]int

View File

@@ -105,6 +105,13 @@ type (
Docs Doc
}
// NestedStruct describes a structure nested in structure.
NestedStruct struct {
RawName string
Members []Member
Docs Doc
}
// PrimitiveType describes the basic golang type, such as bool,int32,int64, ...
PrimitiveType struct {
RawName string

View File

@@ -54,8 +54,8 @@ func writeIndent(writer io.Writer, indent int) {
}
func genTsType(m spec.Member, indent int) (ty string, err error) {
v, ok := m.Type.(spec.DefineStruct)
if ok && v.IsNestedStruct() {
v, ok := m.Type.(spec.NestedStruct)
if ok {
writer := bytes.NewBuffer(nil)
_, err := fmt.Fprintf(writer, "{\n")
if err != nil {

View File

@@ -54,7 +54,7 @@ func (a *Analyzer) astTypeToSpec(in ast.DataType) (spec.Type, error) {
return nil, ast.SyntaxError(v.Pos(), "unsupported empty struct")
}
return spec.DefineStruct{
return spec.NestedStruct{
RawName: v.RawText(),
Members: members,
}, nil
@@ -347,14 +347,12 @@ func (a *Analyzer) fillTypes() error {
for _, member := range v.Members {
switch v := member.Type.(type) {
case spec.DefineStruct:
if !v.IsNestedStruct() {
tp, err := a.findDefinedType(v.RawName)
if err != nil {
return err
}
member.Type = tp
tp, err := a.findDefinedType(v.RawName)
if err != nil {
return err
}
member.Type = tp
}
members = append(members, member)
}