Hey,
we have upgraded to apollo server 2 and now have trouble with the GraphQL context in the subscription resolvers. We have an ApolloServer and will extend the GraphQL context with some data the client sent during the first connect. In the docs is an example.
We've implemeted the onConnect and return some data:
...
subscriptions: {
onConnect: (connectionParams: ConnectionParams) => {
// do sth. with the connection params
return { some: 'data' };
}
}
...
The documentation says the return value of the onConnect function extends the GraphQL context. The onConnect gets executed when a new client connects.
In our resolver we want to do some filtering based on the extended context:
...
subscribe: withFilter(
() => this.pubSub.subscribe('xxx'),
(payload, _, ctx: IGraphQLContext) => {
// do sth. with `ctx.some`
return true;
},
),
But the context in the resolver is always empty.
We are on the latest version of apollo-server-express and subscriptions-transport-ws.
Thank you very much for your help!
The return value of the onConnect callback is available in the context function. So you can return it if you build the context for subscriptions.
...
subscriptions: {
onConnect: async (connectionParams) => {
// Do some stuff with connectionParams like auth
return { extended: 'context' };
},
},
context: async ({ req, connection }) => {
// If we build the context for subscriptions, return the context generated in the onConnect callback.
// In this example `connection.context` is `{ extended: 'context' }`
if (!req || !req.headers) {
return connection.context;
}
// Build context for normal requests
return { regular: 'context' };
},
...
This example could be added to docs. It is awesome in comparison to official documentation.
Most helpful comment
The return value of the
onConnectcallback is available in thecontextfunction. So you can return it if you build the context for subscriptions.