Skip to content

Instantly share code, notes, and snippets.

@Jannis
Last active January 5, 2018 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jannis/e98d230153e8edb02e4a05eb9e505f06 to your computer and use it in GitHub Desktop.
Save Jannis/e98d230153e8edb02e4a05eb9e505f06 to your computer and use it in GitHub Desktop.
Working with GraphQL WebSocket subscriptions in graphqlws
// 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