Looking at all the examples the subscription resolver is of the form:
messageCreated: {
subscribe: () => pubsub.asyncIterator(MESSAGE_CREATED),
}
i.e. it returns an object with a subscribe property. However I need to be able to dynamically set the channel based on the set of parameters coming through from the client, when they subscribe. I would like to request that the subscription resolver be generalized to a function that returns the object with the subscribe property. The resolver should then look like:
messageCreated(variables) {
return {
subscribe: pubsub.asyncIterator(variables.topic),
}
}
After a couple of days of debugging this, I came up with this solution.
I am using _graphql-redis-subscriptions_ library for Redis PubSub
My GraphQL schema:
type Subscription {
updateMarket (event: String): JSON
}
Subscription:
export const Subscription = {
updateMarket: {
subscribe: (model, args, context, info) => {
console.log("SUBSCRIBED TO EVENT: " + args.event);
return PubSub.asyncIterator(args.event);
}
},
As you can see, we can pass arguments to subscribe function:
subscribe: (model, args, context, info)
Apollo Team should update their documentation for subscriptions because this works now.
On the frontend GraphQL Query looks like this:
subscription updateMarket($event: String) {
updateMarket(event: $event)
}
Modules:
"graphql": "^14.0.2",
"apollo-server-express": "^2.1.0",
"graphql-redis-subscriptions": "^2.0.0"
Questions: [email protected]
Best regards,
Mihajlo
Thanks very much for reporting this! We think this is a great idea, and would definitely love a PR for the docs. If you (or anyone else) is interested in working on this, that would be great - thanks!
Most helpful comment
After a couple of days of debugging this, I came up with this solution.
I am using _graphql-redis-subscriptions_ library for Redis PubSub
My GraphQL schema:
type Subscription { updateMarket (event: String): JSON }Subscription:
export const Subscription = { updateMarket: { subscribe: (model, args, context, info) => { console.log("SUBSCRIBED TO EVENT: " + args.event); return PubSub.asyncIterator(args.event); } },As you can see, we can pass arguments to subscribe function:
subscribe: (model, args, context, info)Apollo Team should update their documentation for subscriptions because this works now.
On the frontend GraphQL Query looks like this:
subscription updateMarket($event: String) { updateMarket(event: $event) }Modules:
"graphql": "^14.0.2",
"apollo-server-express": "^2.1.0",
"graphql-redis-subscriptions": "^2.0.0"
Questions: [email protected]
Best regards,
Mihajlo