Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apollo GraphQL server; setting context to handle requests triggered by a fired subscription

I understand how to set the context object when creating a GraphQL server e.g.

const app = express();
app.use(GRAPHQL_URL, graphqlExpress({
            schema,
            context: {
                foo: 'bar'
            },
    }));

so that the context object is passed to my resolvers when handling an incoming request.

However I'm not seeing this context object when the resolvers are triggered by a subscription (i.e. a client subscribes to a GraphQL subscription, and defines the shape of the data to be sent to them when the subscription fires); in that case the context appears to be an empty Object.

Is there way to ensure that my context object is set correctly when resolvers are called following a PubSub.publish() call?

like image 971
wabrit Avatar asked Nov 22 '25 23:11

wabrit


1 Answers

I guess you are using the package subscription-transport-ws. In that case it is possible to add a context value in different execution steps. See API. Two possible scenarios

  1. If you have some kind of authentication. You could add a viewer in the context at the onConnect execution step. This is done at the first connection to the websocket and wont change until the connection is closed and opened again. See example.

  2. If you want to add a context more dynamically you can add a kind of middleware before the execute step.It could look like this:

const middleware = (args) => new Promise((resolve, reject) => {
  const [schema, document, root, context, variables, operation] = args;
  context.foo = "bar"; // add something to context
  resolve(args);
})

subscriptionServer = SubscriptionServer.create({
  schema: executable.schema,
  subscribe,
  execute: (...args) => middleware(args).then(args => {
    return execute(...args);
  })
}, {
  server: websocketServer,
  path: "/graphql",
}, );
like image 146
Locco0_0 Avatar answered Nov 24 '25 22:11

Locco0_0