'Nestjs GraphQL subscriptions onConnect & onDisconnect callbacks

Is there an approach to hook into the onConnect and onDisconnect lifecycle-events in Nestjs?



Solution 1:[1]

In the documentation you'll see it recommends if you're using graph-ws to use the following:

subscriptions: {
        'graphql-ws': true
}

However I had to dig a bit into how to actually get that to work with the lifecycle-events you speak of. Below is an example for Nestjs using TypeScript if you're using graphql-ws:

subscriptions: {
        'graphql-ws': {
          onConnect: (context: Context) => {
            const { connectionParams, subscriptions } = context;
            console.log(
              `connectionParams: ${connectionParams}, subscriptions: ${JSON.stringify(
                subscriptions,
              )}}, context ${JSON.stringify(context)}`,
            );
          },
          onDisconnect: (context: Context) => {
            const { connectionParams, subscriptions } = context;
            console.log(
              `connectionParams: ${JSON.stringify(
                connectionParams,
              )}}, subscriptions: ${JSON.stringify(
                subscriptions,
              )}, context ${JSON.stringify(context)}`,
            );
          },

Solution 2:[2]

It turns out you can provide them in the subscriptions portion of the graphql configuration

 subscriptions: {
    keepAlive: subscriptionsTimeout,
    onConnect: (connectionParams, websocket, context) => {
      console.log(`connectionParams: ${connectionParams}, websocket: ${JSON.stringify(websocket)}}, context ${JSON.stringify(context)}`);
    },
    onDisconnect: ( websocket, context) => {
      console.log(`websocket: ${JSON.stringify(websocket)}}, context ${JSON.stringify(context)}`);
    }
  },

Solution 3:[3]

add path like this : 'graphql-ws': { path: '/subscriptions',

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Shi
Solution 2 cramhead
Solution 3 maamoun toj