Search code examples
gographqlgraphql-go

Resolving list field in GraphQL without struct


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".


Solution

  • 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