diff --git a/src/client.ts b/src/client.ts index cfa152d36..0ff85e74a 100644 --- a/src/client.ts +++ b/src/client.ts @@ -243,6 +243,9 @@ export class SubscriptionClient { this.eventEmitter.emit(isReconnect ? 'reconnect' : 'connect'); this.reconnecting = false; this.backoff.reset(); + // Send INIT message, no need to wait for connection to success (reduce roundtrips) + this.sendMessage({type: INIT, payload: this.connectionParams}); + Object.keys(this.reconnectSubscriptions).forEach((key) => { const { options, handler } = this.reconnectSubscriptions[key]; this.subscribe(options, handler); @@ -251,9 +254,6 @@ export class SubscriptionClient { this.client.send(JSON.stringify(message)); }); this.unsentMessagesQueue = []; - - // Send INIT message, no need to wait for connection to success (reduce roundtrips) - this.sendMessage({type: INIT, payload: this.connectionParams}); }; this.client.onclose = () => { diff --git a/src/test/tests.ts b/src/test/tests.ts index 2417c95f3..d54d2d00d 100644 --- a/src/test/tests.ts +++ b/src/test/tests.ts @@ -216,6 +216,40 @@ describe('Client', function () { new SubscriptionClient(`ws://localhost:${RAW_TEST_PORT}/`); }); + it('should send INIT message first, then the SUBSCRIPTION_START message', (done) => { + let initReceived = false; + + const client = new SubscriptionClient(`ws://localhost:${RAW_TEST_PORT}/`); + wsServer.on('connection', (connection: any) => { + connection.on('message', (message: any) => { + const parsedMessage = JSON.parse(message); + // mock server + if (parsedMessage.type === INIT) { + connection.send(JSON.stringify({type: INIT_SUCCESS, payload: {}})); + initReceived = true; + } + if (parsedMessage.type === SUBSCRIPTION_START) { + expect(initReceived).to.be.true; + client.unsubscribeAll(); + done(); + } + }); + }); + client.subscribe( + { + query: `subscription useInfo { + user(id: 3) { + id + name + } + }`, + }, + (error, result) => { + // do nothing + } + ); + }); + it('should emit connect event for client side when socket is open', (done) => { const client = new SubscriptionClient(`ws://localhost:${TEST_PORT}/`); @@ -304,9 +338,6 @@ describe('Client', function () { }).to.throw(); }); - - - it('should allow both data and errors on SUBSCRIPTION_DATA', (done) => { wsServer.on('connection', (connection: any) => { connection.on('message', (message: any) => {