Skip to content

Conversation

racerxdl
Copy link
Collaborator

@racerxdl racerxdl commented Mar 1, 2020

I added Subscribe function to Object / Fields Definitions so its easier to make GraphQL Subscription Handlers. I only added the field so it wouldn't break compatibility and if you don't use it, it wont make a difference.

So for example in https://github.com/racerxdl/go-subscription-handler I did:

var rootSubscriptions = graphql.ObjectConfig{
    Name: "RootSubscriptions",
    Fields: graphql.Fields{
        "serverTime": &graphql.Field{
            Type: graphql.String,
            Resolve: func(p graphql.ResolveParams) (interface{}, error) {
                err := subhandler.Subscribe(p.Context, "serverTime")

                if p.Source != nil {
                    // We received a event data
                    v, ok := p.Source.(map[string]interface{})
                    if ok && v["time"] != nil {
                        return v["time"], nil
                    }
                }

                // We didn't receive a event data, so resolve normally
                return time.Now().String(), err
            },
        },
    },
}

With that Subscribe field in the struct I could do:

var rootSubscriptions = graphql.ObjectConfig{
    Name: "RootSubscriptions",
    Fields: graphql.Fields{
        "serverTime": &graphql.Field{
            Type: graphql.String,
            Subscribe: func(p graphql.ResolveParams) error {
                return subhandler.Subscribe(p.Context, "serverTime")
            },
            Resolve: func(p graphql.ResolveParams) (interface{}, error) {
                if p.Source != nil {
                    // We received a event data
                    v, ok := p.Source.(map[string]interface{})
                    if ok && v["time"] != nil {
                        return v["time"], nil
                    }
                }

                // We didn't receive a event data, so resolve normally
                return time.Now().String(), err
            },
        },
    },
}

That should help with graphql-go#242

Ref: https://github.com/graphql-go/graphql/pulls

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant