Skip to content

Commit

Permalink
Merge pull request #2366 from jkossis/properly-close-ws
Browse files Browse the repository at this point in the history
fix(@nestjs/graphql): need to properly close websocket servers
  • Loading branch information
kamilmysliwiec committed Sep 1, 2022
2 parents 0ccd842 + cdbf86c commit 43e5420
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 10 deletions.
2 changes: 1 addition & 1 deletion packages/apollo/tests/subscriptions/compat.spec.ts
Expand Up @@ -169,7 +169,7 @@ describe('Use graphql-ws + subscriptions-transport-ws', () => {
try {
await wsClient?.dispose();
} catch {}
await subWsClient?.close();
subWsClient?.close();
await app.close();
jest.clearAllMocks();
});
Expand Down
20 changes: 11 additions & 9 deletions packages/graphql/lib/services/gql-subscription.service.ts
Expand Up @@ -3,7 +3,11 @@ import {
GraphQLSchema,
subscribe as graphqlSubscribe,
} from 'graphql';
import { GRAPHQL_TRANSPORT_WS_PROTOCOL, ServerOptions } from 'graphql-ws';
import {
Disposable,
GRAPHQL_TRANSPORT_WS_PROTOCOL,
ServerOptions,
} from 'graphql-ws';
import { useServer } from 'graphql-ws/lib/use/ws';
import {
GRAPHQL_WS,
Expand Down Expand Up @@ -51,6 +55,8 @@ export interface GqlSubscriptionServiceOptions extends SubscriptionConfig {
export class GqlSubscriptionService {
private readonly wss: ws.Server;
private readonly subTransWs: ws.Server;
private wsGqlDisposable: Disposable;
private subServer: SubscriptionServer;

constructor(
private readonly options: GqlSubscriptionServiceOptions,
Expand Down Expand Up @@ -83,7 +89,7 @@ export class GqlSubscriptionService {
const graphqlWsOptions =
this.options['graphql-ws'] === true ? {} : this.options['graphql-ws'];
supportedProtocols.push(GRAPHQL_TRANSPORT_WS_PROTOCOL);
useServer(
this.wsGqlDisposable = useServer(
{
schema: this.options.schema,
execute,
Expand All @@ -102,7 +108,7 @@ export class GqlSubscriptionService {
: this.options['subscriptions-transport-ws'];

supportedProtocols.push(GRAPHQL_WS);
SubscriptionServer.create(
this.subServer = SubscriptionServer.create(
{
schema: this.options.schema,
execute,
Expand Down Expand Up @@ -139,11 +145,7 @@ export class GqlSubscriptionService {
}

async stop() {
for (const client of this.wss.clients) {
client.close(1001, 'Going away');
}
for (const client of this.subTransWs.clients) {
client.close(1001, 'Going away');
}
await this.wsGqlDisposable?.dispose();
this.subServer?.close();
}
}

0 comments on commit 43e5420

Please sign in to comment.