英文:
Resolving list field in GraphQL without struct
问题
我有这个GraphQL类型:
type User struct {
ID string
Name 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) {
users := []map[string]string{
map[string]string{
"id": "1",
"name": "John",
},
map[string]string{
"id": "2",
"name": "Jess",
},
}
return users, nil
},
},
},
})
但它不起作用。查询结果中的每个属性都是nil
。有没有办法解决这个问题?请记住,我不能创建User
结构体。这必须是"通用"的。
英文:
I have this GraphQL type:
type User {
id: String
name: String
}
defined by
var UserObject = graphql.NewObject(graphql.ObjectConfig{
Name: "User",
Fields: graphql.Fields{
"id": &graphql.Field{
Type: graphql.String,
},
"name": &graphql.Field{
Type: graphql.String,
},
},
})
In my root query, I want to link some users with the query field 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
As you see, I have a User
and Users
data types. So far, so good.
Now, imagine I can't create the User
nor Users
structs, what could I return in Resolve
function instead of them?
I thought about a []map[string]string
. It would be something like this:
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
},
},
},
})
But it doesn't work. Every property is nil
in the query result. Is there a way to solve this? Remember I can't create the User
struct. This has to be "generic".
答案1
得分: 2
你可以使用map[string]interface{}
而不是map[string]string
,它应该可以工作。为什么呢?我不太清楚,我找不到任何关于FieldResolveFn
返回值的可接受内容的文档。
users := []map[string]interface{}{{
"id": "1",
"name": "John",
}, {
"id": "2",
"name": "Jess",
}}
return users, nil
英文:
You can use map[string]interface{}
instead of map[string]string
and it should work. Why that is? I don't really know, I couldn't find any docs as to what's acceptable as the return value from FieldResolveFn
.
users := []map[string]interface{}{{
"id": "1",
"name": "John",
}, {
"id": "2",
"name": "Jess",
}}
return users, nil
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论