小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《在 Go 中创建循环 GraphQL 类型》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!
我正在尝试创建两种 graphql 类型:item 和 listing,它们包含彼此的实例作为字段。在 graphql 类型语言中,它们将是:
type item {
id: id!
name: string!
...
listings: [listing]!
}
type listing {
id: id!
price: int!
...
item: item!
}
(...代表不相关的省略字段)
我见过其他项目这样做,所以我知道这是可能的,但我在使用 github.com/graphql-go/graphql 时遇到困难。根据我在网上了解到的使用 go 执行此操作的方法是:
var itemtype graphql.type = graphql.newobject(
graphql.objectconfig {
name: "item",
fields: graphql.fields {
"id": &graphql.field {
type: graphql.id,
},
"name": &graphql.field {
type: graphql.string,
},
...
"listings": &graphql.field {
type: graphql.newlist(listingtype),
},
},
},
)
var listingtype graphql.type = graphql.newobject(
graphql.objectconfig {
name: "listing",
fields: graphql.fields {
"id": &graphql.field {
type: graphql.id,
},
"price": &graphql.field {
type: graphql.int,
},
...
"item": &graphql.field {
type: itemtype,
},
},
},
)
但这会导致初始化循环:
./test.go:9:5: initialization loop:
/home/william/Desktop/test.go:9:5: ItemType refers to
/home/william/Desktop/test.go:26:5: ListingType refers to
/home/william/Desktop/test.go:9:5: ItemType
我知道发生这种情况是因为编译器需要知道 itemtype 的大小才能确定 listingtype 的大小,从而确定 itemtype 的大小(等等......),但我不确定如何来绕过它。
解决方案
处理这个问题的recommended way是使用addfieldconfig:
houseType := &graphql.Object{...}
residentType := &graphql.Object{...}
houseType.AddFieldConfig("residents", &graphql.Field{Type: graphql.NewList(residentType)})
residentType.AddFieldConfig("houses", &graphql.Field{Type: graphql.NewList(houseType)})今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~
本文内容来源于互联网,如有侵权请联系删除。
