cramhead
cramhead

Reputation: 1067

Nestjs GraphQL subscriptions onConnect & onDisconnect callbacks

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

Upvotes: 5

Views: 1910

Answers (3)

maamoun toj
maamoun toj

Reputation: 1

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

Upvotes: 0

David Shi
David Shi

Reputation: 206

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)}`,
            );
          },

Upvotes: 4

cramhead
cramhead

Reputation: 1067

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)}`);
    }
  },

Upvotes: 3

Related Questions