graphql-go / graphql

An implementation of GraphQL for Go / Golang
MIT License
9.89k stars 840 forks source link

Accessing parent from nested child resolver #695

Open clarkmcc opened 3 months ago

clarkmcc commented 3 months ago

In the following example, I want to resolve the value in C, but I need the IDs of both A and B to do it. p.Source only gives me B, but not A. What is the proper way to solve this problem?

var a = graphql.NewObject(graphql.ObjectConfig{
    Name: "A",
    Fields: graphql.Fields{
        "id": &graphql.Field{Type: graphql.String},
        "b": &graphql.Field{Type: graphql.NewObject(graphql.ObjectConfig{
            Name: "B",
            Fields: graphql.Fields{
                "id": &graphql.Field{Type: graphql.String},
                "c": &graphql.Field{Type: graphql.NewObject(graphql.ObjectConfig{
                    Name: "C",
                    Fields: graphql.Fields{
                        "value": &graphql.Field{
                            Type: graphql.String,
                            Resolve: func(p graphql.ResolveParams) (interface{}, error) {
                                // I need the ID of A to resolve the value of C
                                return nil, nil
                            },
                        },
                    },
                })},
            },
        })},
    },
})
spasarok commented 3 months ago

You should be able to handle this using Go's context.Context type. See this explanation:

One benefit of using context.Context in a program is the ability to access data stored inside a context. By adding data to a context and passing the context from function to function, each layer of a program can add additional information about what’s happening.

In other words, you can have resolvers A and B add their IDs to the context, and then resolver C can look up those IDs. I hope this helps, and others can correct me if there's a better pattern.