From 61703070bca1cff70d5f6545fdcca66200821544 Mon Sep 17 00:00:00 2001 From: dotansimha Date: Sun, 4 Jun 2017 14:00:45 +0200 Subject: [PATCH] fix issue with reconnect after manual close, and added unit tests for client-server flow --- src/client.ts | 9 +++++---- src/test/tests.ts | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/src/client.ts b/src/client.ts index d048a3a42..5a7f81674 100644 --- a/src/client.ts +++ b/src/client.ts @@ -116,17 +116,18 @@ export class SubscriptionClient { public get status() { if (this.client === null) { - return 0; //readyState 'CONNECTING' + return this.wsImpl.CLOSED; } return this.client.readyState; } - public close() { + public close(isForced = true) { if (this.client !== null) { - this.forceClose = true; + this.forceClose = isForced; this.sendMessage(undefined, MessageTypes.GQL_CONNECTION_TERMINATE, null); this.client.close(); + this.client = null; } } @@ -423,7 +424,7 @@ export class SubscriptionClient { } private checkConnection() { - this.wasKeepAliveReceived ? this.wasKeepAliveReceived = false : this.close(); + this.wasKeepAliveReceived ? this.wasKeepAliveReceived = false : this.close(false); } private connect() { diff --git a/src/test/tests.ts b/src/test/tests.ts index ea9d7368e..3cafe6b22 100644 --- a/src/test/tests.ts +++ b/src/test/tests.ts @@ -1936,6 +1936,47 @@ describe('Message Types', function () { }); describe('Client<->Server Flow', () => { + it('should reconnect after manually closing the connection and then resubscribing', (done) => { + const testServer = createServer(notFoundRequestListener); + testServer.listen(SERVER_EXECUTOR_TESTS_PORT); + + SubscriptionServer.create({ + schema: subscriptionsSchema, + execute, + subscribe, + }, { + server: testServer, + path: '/', + }); + + const client = new SubscriptionClient(`ws://localhost:${SERVER_EXECUTOR_TESTS_PORT}/`); + let isFirstTime = true; + + client.onConnected(async () => { + // Manually close the connection only in the first time, to avoid infinite loop + if (isFirstTime) { + isFirstTime = false; + + setTimeout(() => { + // Disconnect the client + client.close(); + + // Subscribe to data, without manually reconnect before + const opId = client.subscribe({ + query: `query { testString }`, + variables: {}, + }, (err, res) => { + expect(opId).not.to.eq(null); + expect(err).to.eq(null); + expect(res.testString).to.eq('value'); + testServer.close(); + done(); + }); + }, 300); + } + }); + }); + it('should close iteration over AsyncIterator when client unsubscribes', async () => { subscriptionAsyncIteratorSpy.reset(); resolveAsyncIteratorSpy.reset();