From 5a7555a6ecd8f86e0250d04030ce371d5f7352f6 Mon Sep 17 00:00:00 2001 From: John Guo Date: Wed, 6 Oct 2021 14:45:29 +0800 Subject: [PATCH] fix issue in goai for recursive attribute --- protocol/goai/goai_shema.go | 4 ++++ protocol/goai/goai_test.go | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/protocol/goai/goai_shema.go b/protocol/goai/goai_shema.go index 45a308802..21e182614 100644 --- a/protocol/goai/goai_shema.go +++ b/protocol/goai/goai_shema.go @@ -78,10 +78,14 @@ func (oai *OpenApiV3) doAddSchemaSingle(object interface{}) error { reflectType = reflect.TypeOf(object) structTypeName = gstr.SubStrFromREx(reflectType.String(), ".") ) + // Already added. if _, ok := oai.Components.Schemas[structTypeName]; ok { return nil } + // Take the holder first. + oai.Components.Schemas[structTypeName] = SchemaRef{} + structFields, _ := structs.Fields(structs.FieldsInput{ Pointer: object, RecursiveOption: structs.RecursiveOptionEmbeddedNoTag, diff --git a/protocol/goai/goai_test.go b/protocol/goai/goai_test.go index 7f4c4faf3..cf4fa463f 100644 --- a/protocol/goai/goai_test.go +++ b/protocol/goai/goai_test.go @@ -123,3 +123,40 @@ func TestOpenApiV3_Add(t *testing.T) { t.Assert(len(oai.Paths[`/test2/{appId}`].Post.Parameters), 2) }) } + +func TestOpenApiV3_Add_Recursive(t *testing.T) { + type CategoryTreeItem struct { + Id uint `json:"id"` + ParentId uint `json:"parent_id"` + Items []*CategoryTreeItem `json:"items,omitempty"` + } + + type CategoryGetTreeReq struct { + gmeta.Meta `path:"/category-get-tree" method:"GET" tags:"default"` + ContentType string `in:"query"` + } + type CategoryGetTreeRes struct { + List []*CategoryTreeItem + } + + f := func(ctx context.Context, req *CategoryGetTreeReq) (res *CategoryGetTreeRes, err error) { + return + } + + gtest.C(t, func(t *gtest.T) { + var ( + err error + oai = goai.New() + ) + err = oai.Add(goai.AddInput{ + Path: "/tree", + Object: f, + }) + t.AssertNil(err) + t.AssertNil(err) + // Schema asserts. + t.Assert(len(oai.Components.Schemas), 3) + t.Assert(oai.Components.Schemas[`CategoryTreeItem`].Value.Type, goai.TypeObject) + t.Assert(len(oai.Components.Schemas[`CategoryTreeItem`].Value.Properties), 3) + }) +}