0

我有这个 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

如您所见,我有一个UserUsers数据类型。到现在为止还挺好。

现在,想象一下我无法创建UsernorUsers结构,我可以在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结构。这必须是“通用的”。

4

1 回答 1

2

您可以使用map[string]interface{}代替,map[string]string它应该可以工作。为什么会这样?我真的不知道,我找不到任何关于什么是可接受的返回值的文档FieldResolveFn

users := []map[string]interface{}{{
    "id":   "1",
    "name": "John",
}, {
    "id":   "2",
    "name": "Jess",
}}
return users, nil
于 2017-04-12T16:23:37.823 回答