Last active
January 5, 2018 13:41
-
-
Save Jannis/e98d230153e8edb02e4a05eb9e505f06 to your computer and use it in GitHub Desktop.
Working with GraphQL WebSocket subscriptions in graphqlws
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This assumes you have access to the above subscription manager | |
subscription := subscriptionManager.Subscriptions() | |
for _, conn := range subscriptions { | |
// Things you have access to here: | |
conn.ID() // The connection ID | |
conn.User() // The user returned from the subscription manager's Authenticate | |
for _, subscription := range subscriptions[conn] { | |
// Things you have access to here: | |
subscription.ID // The subscription ID (unique per conn) | |
subscription.OperationName // The name of the subcription | |
subscription.Query // The subscription query/queries string | |
subscription.Variables // The subscription variables | |
subscription.Document // The GraphQL AST for the subscription | |
subscription.Fields // The names of top-level queries | |
subscription.Connection // The GraphQL WS connection | |
// Prepare an execution context for running the query | |
ctx := context.Context() | |
// Re-execute the subscription query | |
params := graphql.Params{ | |
Schema: schema, // The GraphQL schema | |
RequestString: subscription.Query, | |
VariableValues: subscription.Variables, | |
OperationName: subscription.OperationName, | |
Context: ctx, | |
} | |
result := graphql.Do(params) | |
// Send query results back to the subscriber at any point | |
data := graphqlws.DataMessagePayload{ | |
// Data can be anything (interface{}) | |
Data: result.Data, | |
// Errors is optional ([]error) | |
Errors: graphqlws.ErrorsFromGraphQLErrors(result.Errors), | |
} | |
subscription.SendData(&data) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment