我有这个 GraphQL 类型:
type User {
id: String
name: String
}
被定义为
var UserObject = graphql.NewObject(graphql.ObjectConfig{
Name: "User",
Fields: graphql.Fields{
"id": &graphql.Field{
Type: graphql.String,
},
"name": &graphql.Field{
Type: graphql.String,
},
},
})
在我的根查询中,我想将一些用户与查询字段链接users
:
var RootQuery = graphql.NewObject(graphql.ObjectConfig{
Name: "RootQuery",
Fields: graphql.Fields{
"users": &graphql.Field{
Type: graphql.NewList(UserObject),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return Users{
User{
ID: "1",
NAME: "John",
},
User{
ID: "2",
NAME: "Jess"
}
}, nil
},
},
},
})
type User struct {
ID string
NAME string
}
type Users []User
如您所见,我有一个User
和Users
数据类型。到现在为止还挺好。
现在,想象一下我无法创建User
norUsers
结构,我可以在Resolve
函数中返回什么而不是它们?
我想了一个[]map[string]string
。它会是这样的:
var RootQuery = graphql.NewObject(graphql.ObjectConfig{
Name: "RootQuery",
Fields: graphql.Fields{
"users": &graphql.Field{
Type: graphql.NewList(UserObject),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
users := []map[string]string {
map[string]string {
"id" : "1",
"name" : "John",
},
map[string]string {
"id" : "2",
"name" : "Jess",
},
}
return users, nil
},
},
},
})
但它不起作用。每个属性都nil
在查询结果中。有没有办法解决这个问题?请记住我无法创建User
结构。这必须是“通用的”。